如何在Dynamic Sql中添加变量,而不是连接它们?

时间:2009-11-12 21:14:14

标签: tsql dynamic-sql

我有以下动态sql语句,我想添加@StartRowIndex + @MaximumRows并从中减去1。我不清楚将单引号放在声明中的位置。这是:

SET @sql = @sql + ' SELECT *
 FROM
LicenseInfo
WHERE RowNum 
BETWEEN ' + @StartRowIndex + ' AND ' + 
'(' + @StartRowIndex + @MaximumRows + ')'  -  1
+ ' ORDER BY cnt desc'

3 个答案:

答案 0 :(得分:3)

创建新变量@EndRowIndex并在构造动态sql语句之前计算它。

类似的东西:

DECLARE @EndRowIndex int

SET @EndRowIndex = @StartRowIndex + @MaximumRows - 1

SET @sql = @sql + ' SELECT *
 FROM
LicenseInfo
WHERE RowNum 
BETWEEN ' + @StartRowIndex + ' AND ' + @EndRowIndex 
+ ' ORDER BY cnt desc'

答案 1 :(得分:2)

您需要将int参数转换为varchar

SET @sql = @sql + ' SELECT *
 FROM
LicenseInfo
WHERE RowNum 
BETWEEN ' + @StartRowIndex + ' AND ' + 
'(' + CAST(@StartRowIndex as varchar(10)) + CAST(@MaximumRows as varchar(10)) + ') - 1  
 ORDER BY cnt desc'

答案 2 :(得分:2)

声明变量,进行计算并在生成SQL语句时将其CAST到varchar

DECLARE @LastRowIndex int

SET @LastRowIndex = @StartRowIndex + @MaximumRows - 1

SET @sql = @sql + ' 
SELECT *
FROM LicenseInfo
WHERE 1=1
AND RowNum BETWEEN ' + CAST (@StartRowIndex as VarChar) + 
' AND ' + CAST (@LastRowIndex as VarChar)
+ ' ORDER BY cnt DESC'

为了让SQL Server连接字符串值,你必须进行强制转换,否则它会尝试将nVarChar转换为数字并尝试将它们添加为数字。