執行帶嵌入引數的sql

2021-04-17 20:23:35 字數 2088 閱讀 3652

通常執行sql語句,大家用的都是exec,exec功能強大,但不支援嵌入引數,sp_executesql解決了這個問題。抄一段sqlserver幫助:

sp_executesql

執行可以多次重用或動態生成的 transact-sql 語句或批處理。transact-sql 語句或批處理可以包含嵌入引數。

語法

sp_executesql[@stmt=]

stmt

引數

[@stmt=]

stmt

包含 transact-sql 語句或批處理的 unicode 字串,

stmt 必須是可以隱式轉換為ntext的 unicode 常量或變數。不允許使用更複雜的 unicode 表示式(例如使用 + 運算子串聯兩個字串)。不允許使用字元常量。如果指定常量,則必須使用 n 作為字首。例如,unicode 常量 n'sp_who' 是有效的,但是字元常量 'sp_who' 則無效。字串的大小僅受可用資料庫伺服器記憶體限制。

stmt 可以包含與變數名形式相同的引數,例如:

n'select * from employees where employeeid = @idparameter'
stmt 中包含的每個引數在@params引數定義列表和引數值列表中均必須有對應項。

[@params=]n'@parameter_name  data_type [,...

n]'

字串,其中包含已嵌入到

stmt 中的所有引數的定義。該字串必須是可以隱式轉換為ntext的 unicode 常量或變數。每個引數定義均由引數名和資料型別組成。

n 是表明附加引數定義的佔位符。

stmt 中指定的每個引數都必須在@params中定義。如果

stmt 中的 transact-sql 語句或批處理不包含引數,則不需要@params。該引數的預設值為 null。

[@param1=]'value1'

引數字串中定義的第乙個引數的值。該值可以是常量或變數。必須為

stmt 中包含的每個引數提供引數值。如果

stmt 中包含的 transact-sql 語句或批處理沒有引數,則不需要值。 n

附加引數的值的佔位符。這些值只能是常量或變數,而不能是更複雜的表示式,例如函式或使用運算子生成的表示式。

返回**值

0(成功)或 1(失敗)

結果集

從生成 sql 字串的所有 sql 語句返回結果集。

例子(感謝鄒建提供)

declare @user varchar(1000)

declare @motable varchar(20)

select @motable = 'mt_10'

declare @sql nvarchar(4000)  --定義變數,注意型別

set @sql='select @user = count(distinct userid)  from

'+@motable  --為變數賦值

--執行@sql中的語句

exec sp_executesql @sql

,n'@user varchar(1000) out'  --表示@sql中的語句包含了乙個輸出引數

,@user out --和呼叫儲存過程差不多,指定輸出引數值

print @user

對access執行帶引數的sql語句

oledbcommand cmd new oledbcommand string conn1 lyy.dbutility.dbhelperoledb.connectionstring oledbconnection con new oledbconnection conn1 cmd.connecti...

SqlParameter類 帶引數的SQL語句

sqlparameter 類 表示 sqlcommand 的引數,也可以是它到 dataset 列的對映。無法繼承此類。命名空間 system.data.sqlclient 程式集 system.data 在 system.data.dll 中 舉例1 string strconn data sou...

SqlParameter類 帶引數的SQL語句

sqlparameter 類 表示 sqlcommand 的引數,也可以是它到 dataset 列的對映。無法繼承此類。命名空間 system.data.sqlclient 程式集 system.data 在 system.data.dll 中 舉例1 string strconn data sou...