我想根据用户输入声明多个变量,并将它们全部用作WHERE子句中的条件。我将变量硬设置为我想要测试的值。我计划将来以类似的方式使用@Well
和@Analyst
变量。这是代码:
DECLARE @Analysis nvarchar(20)
DECLARE @SQLQuery nvarchar(max)
DECLARE @Formation nvarchar(50)
DECLARE @Well nvarchar(30)
DECLARE @Analyst nvarchar(50)
SET @Analysis = 'Elemental Analysis'
SET @Formation = 'Bruce'
SET @SQLQuery = N'SELECT TB_Projects.JobLog#, TB_Projects.ProjName, COUNT(TB_Samples.Sample#) AS [Total Samples]
FROM TB_Projects INNER JOIN TB_Samples ON TB_Projects.JobLog# = TB_Samples.JobLog#
WHERE TB_Samples.['+ @Analysis +'] = 1 AND TB_Projects.Formation ='+@Formation+' GROUP BY TB_Projects.JobLog#, TB_Projects.ProjName'
EXECUTE(@SQLQuery)
我使用以下代码收到以下错误:
Msg 207,Level 16,State 1,Line 3 列名称'Bruce'无效。
'Bruce'应该是TB_Projects.Formation列返回的值,它不是列名。为什么这不起作用?
答案 0 :(得分:1)
你在字符串中有这个:
TB_Projects.Formation = '+@Formation+'
这变成了:
TB_Projects.Formation = Bruce
看到问题?如果在运行之前打印出字符串,问题可能就很明显了。
最简单的解决方案是:
TB_Projects.Formation = '''+@Formation+'''
这将添加单引号。
更好的解决方案是使用sp_executesql
和值的参数。
答案 1 :(得分:-1)
你需要将形成值用单引号括起来:
SET @SQLQuery = N'SELECT TB_Projects.JobLog#, TB_Projects.ProjName, COUNT(TB_Samples.Sample#) AS [Total Samples]
FROM TB_Projects INNER JOIN TB_Samples ON TB_Projects.JobLog# = TB_Samples.JobLog#
WHERE TB_Samples.['+ @Analysis +'] = 1 AND TB_Projects.Formation ='''+@Formation+''' GROUP BY TB_Projects.JobLog#, TB_Projects.ProjName'
EXECUTE(@SQLQuery)