TOP字句加SQL變量的相關(guān)問題
SQL Server數(shù)據(jù)庫中的變量可以加載TOP字句之后,下文將對TOP字句加SQL變量的相關(guān)問題進行討論,供您參考,希望對您學(xué)習(xí)SQL數(shù)據(jù)庫有所幫助。
SQL Server2005開始,TOP子句后可以跟常量或者變量,跟常量時可省略括號,即top(2)和top 2是等價的(注意不加括號時top和2間的空格),top后使用SQL變量時必須使用括號,例:
Sql代碼
declare @num int
set @num = 10
select top(@num) * from sys.tables
declare @num int
set @num = 10
select top(@num) * from sys.tables
使用動態(tài)SQL為:
Sql代碼
declare @num int
set @num = 10
declare @str nvarchar(1000)
set @str = 'select top('+cast(@num as nvarchar(10))+') * from sys.tables'
exec(@str)
declare @num int
set @num = 10
declare @str nvarchar(1000)
set @str = 'select top('+cast(@num as nvarchar(10))+') * from sys.tables'
exec(@str)
關(guān)于exec的一些備注:
1.使用exec命令時,括號中只允許包含一個字符變量,或者一個字符串文本,或者字符串變量與字符串文本的串聯(lián)。不能在括號中使用函數(shù)或CASE表達式,所以最好將代碼放在一個變量中,再把此SQL變量作為exec命令的參數(shù)
2.exec(<string>)不提供接口,因此動態(tài)批處理不能訪問在調(diào)用批處理中定義的局部變量,必須把變量內(nèi)容串聯(lián)到字符串中,就像上面的例子一樣。上面動態(tài)SQL的例子如果寫為 Sql代碼
set @str = 'select top('+@num +') * from sys.tables';
exec(@str)
set @str = 'select top('+@num +') * from sys.tables';
exec(@str)
則會報錯
3.同樣的exec也不支持輸出參數(shù),如果要把輸入放進一個SQL變量,必須先把輸入插入一個目標表,然后再從目標表例取值賦給該變量
【編輯推薦】