I am writing a dynamic query in SSMS 2008 and I get the above error. What is the cause of this?
My query:
SELECT TOP 10 *
FROM
ALL_COMPLAINTS A
JOIN
#TEMP5 B ON A.QXP_EXCEPTION_NO = B.QXP_EXCEPTION_NO
AND A.[LEVEL] = B.[LE开发者_开发知识库VEL]
AND A.[QXP_REPORT_DATE] = B.[QXP_REPORT_DATE]
WHERE
A.QXP_REPORT_DATE >= CONVERT(DATETIME, '' + @FirstMonthDate + ' 00:00:00', 102)
AND
A.QXP_REPORT_DATE <= CONVERT(DATETIME, '' + @LastMonthDate + ' 23:59:59', 102)
AND
A.QXP_SHORT_DESC <> 'Design Control' AND A.LEVEL = ' + CAST(@TheLevel AS VARCHAR(5)) + '
I know that A.Level
is numeric and I also know that I do not get any errors if I just remove the A.Level
portion. However, I am not certain I am casting @TheLevel
correctly since this is dynamic SQL.
Your quotes are messed up in the last line, you cant mix dynamic and non dynamic SQL in the same statement. Also assuming @TheLevel is a numeric, if @TheLevel is a char, you need to convert it to a numeric (int I assume in this case)
SELECT TOP 10 *
FROM
ALL_COMPLAINTS A
JOIN
#TEMP5 B ON A.QXP_EXCEPTION_NO = B.QXP_EXCEPTION_NO
AND A.[LEVEL] = B.[LEVEL]
AND A.[QXP_REPORT_DATE] = B.[QXP_REPORT_DATE]
WHERE
A.QXP_REPORT_DATE >= CONVERT(DATETIME, '' + @FirstMonthDate + ' 00:00:00', 102)
AND
A.QXP_REPORT_DATE <= CONVERT(DATETIME, '' + @LastMonthDate + ' 23:59:59', 102)
AND
A.QXP_SHORT_DESC <> 'Design Control' AND A.LEVEL = @TheLevel
If you need a dynamic portion then it is probably good practice to pre evaluate it and then key it into the non dynamic query
精彩评论