传递参数以插入查询

时间:2011-10-26 13:34:25

标签: asp.net sql sql-server

DECLARE @SQL1 VARCHAR(MAX)
SET @SQL1='SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer='+CAST(@ResponsibleEngineer AS VARCHAR(500))+''
EXEC(@SQL1)
IF @@ROWCOUNT>0
BEGIN
SET @Result='EXIST'

上面的查询由于我将参数@ResponsibleEngineer传递给查询的方式而无法执行。错误是"Invalid column name TEST"TEST是我作为参数值传递的值 @ResponsibleEngineer并且表中没有TEST这样的列。传递参数以插入查询时的错误是什么?

5 个答案:

答案 0 :(得分:3)

参数:

周围需要有标记
'SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer='''+CAST(@ResponsibleEngineer AS VARCHAR(500))+''''

否则你正在产生:

SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer=TEST'

因此它寻找一列TEST。通过在生成的语音标记中包含参数:

SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer='TEST'

此查询将运行WHERE子句,其中ResponsibleEngineer列等于字符串值TEST

答案 1 :(得分:0)

您必须声明@ResponsibleEngineer并设置其值。它基本上用作变量。

DECLARE @ResponsibleEngineer varchar(10)
SET @ResponsibleEngineer = 'my test'

答案 2 :(得分:0)

试试这个:

DECLARE @SQL1 VARCHAR(MAX)
    SET @SQL1='SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer='''+CAST(@ResponsibleEngineer AS VARCHAR(500))+''''
    EXEC(@SQL1)
    IF @@ROWCOUNT>0
    BEGIN
    SET @Result='EXIST'

答案 3 :(得分:0)

您的查询正在转换为

 SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer=TEST

您需要获得以下内容:

 SELECT * FROM tblResponsibleEngineer WHERE ResponsibleEngineer='TEST'

答案 4 :(得分:0)

删除选择周围的空格。快速样本

DECLARE cnt int
SELECT cnt= count(*) FROM tblResponsibleEngineer WHERE ResponsibleEngineer='CAST(@ResponsibleEngineer AS VARCHAR(500))'
IF cnt>0
BEGIN
  SET @Result='EXIST'

希望这有帮助。