How to add variables in Dynamic Sql, not concatenate them?
-
19-09-2019 - |
Question
I have the following dynamic sql statement where I want to add @StartRowIndex + @MaximumRows and subtract 1 from it. I am unclear on where to put the single quotes in the statement. Here it is:
SET @sql = @sql + ' SELECT *
FROM
LicenseInfo
WHERE RowNum
BETWEEN ' + @StartRowIndex + ' AND ' +
'(' + @StartRowIndex + @MaximumRows + ')' - 1
+ ' ORDER BY cnt desc'
Solution
Create new variable @EndRowIndex
and calculate it before you construct the dynamic sql statement.
Something like:
DECLARE @EndRowIndex int
SET @EndRowIndex = @StartRowIndex + @MaximumRows - 1
SET @sql = @sql + ' SELECT *
FROM
LicenseInfo
WHERE RowNum
BETWEEN ' + @StartRowIndex + ' AND ' + @EndRowIndex
+ ' ORDER BY cnt desc'
OTHER TIPS
You need to cast the int parameters into 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'
Declare a variable, do the calculation and CAST it to varchar when generating the SQL statement
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'
You have to cast in order to let SQL Server concatenate string values, otherwise it will try to convert the nVarChar to number and try to add them as numerics.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow