2013-11-28 32 views
0

這個想法是有一個通用的存儲過程來從所有表中獲取數據。此查詢給出錯誤不正確的語法 - T-Sql

不正確的語法new @OrderByClause。

我哪裏錯了?

declare @TableName nvarchar(50), @ColName nvarchar(50), 
     @OrderByClause nvarchar(50), @Code nvarchar(max), 
     @StartIndex nvarchar(50), @EndIndex nvarchar(50) 

set @TableName = 'tblCountry' 
set @ColName = 'countryname' 
set @OrderByClause = 'desc' 
set @StartIndex = '2' 
set @EndIndex = '10' 

select @Code = 'With temp as (select row_number() 
       over (order by @ColName @OrderByClause) as row, * from @TableName) 
       select * from temp where row between @StartIndex and @EndIndex' 

set @param = '@TableName nvarchar(50), @ColName nvarchar(50), 
       @OrderByClause nvarchar(50), @StartIndex nvarchar(50), 
       @EndIndex nvarchar(50)' 

execute sp_executesql @Code, @param @colname, @OrderByClause, @TableName, 
         @StartIndex, @EndIndex 

編輯

這是工作雖然....

select @code = 'with temp as (select row_number() over (order by '+ 
       @colname+' '[email protected]+') as row, * from '[email protected]+') 
select * from temp where row between '[email protected]+' and '[email protected] 

execute sp_executesql @code 
+1

你不能參數化的SQL的任意部分,你是試。這裏使用動態SQL的要點是首先爲無法參數化的部分通過串聯創建所需的字符串。閱讀SQL注入和'QUOTENAME'函數[here](http://www.sommarskog.se/dynamic_sql.html) –

回答

2

你錯過了最後一條語句逗號:

execute sp_executesql @Code, @param @colname, @OrderByClause, @TableName, 

應該

execute sp_executesql @Code, @param, @colname, @OrderByClause, @TableName, 

的第二件事情是,@RahulTripathi是正確的(但出於不同的原因),這是無效的:

select @Code = 'With temp as (select row_number() 
      over (order by @ColName @OrderByClause) as row, * from @TableName) 
      select * from temp where row between @StartIndex and @EndIndex' 

@OrderByClause不能有,因爲ASCDESC語法元素條款ORDER BY,不能是變量。

接下來,您尚未在動態SQL中正確定義@TableName。您在上述命令中使用它作爲表變量,但是您正在傳遞(並將其定義爲)NVarchar(50)

+2

問題中顯示的SQL字符串不會按預期工作! –

+0

哎呀我的錯誤,逗號存在於查詢 – Ruby

+0

@Ruby更新回答.. – RBarryYoung

0

我想你的變量在sp_executesql範圍中既沒有被定義也沒有被定義(在desc的情況下)。 嘗試調用sp_executesql的用+,當你分配@code報價之前,「擴大」:

select @Code = 'With temp as (select row_number() 
       over (order by '+ @ColName +' '+ @OrderByClause +') as row, * from '+ @TableName +') 
       select * from temp where row between '+ @StartIndex + ' and '[email protected] 

(只做一行)

,或者你可以將參數傳遞給sp_executesql的,但你將不得不選擇不同名 而不是@ColName,@tablename和@OrderByClause我猜(你不能把變量而不是SQL文本查詢中的任何地方)

select @Code = 'With temp as (select row_number() 
       over (order by '[email protected]+' '[email protected]+') as row, * from '[email protected]+') 
       select * from temp where row between @pStartIndex and @pEndIndex' 
execute sp_executesql @code, @[email protected], @[email protected]