在局部变量存储过程中输入等于(=)

时间:2015-11-06 08:35:45

标签: sql sql-server tsql variables stored-procedures

简单的问题,但浪费时间寻找答案。我有这样的存储过程

ALTER PROCEDURE [dbo].[sinau]   

    @id varchar (max)
    AS
 BEGIN

SET NOCOUNT ON;
declare
@select varchar (4000),
@from varchar (4000),
@where varchar (4000),
@final varchar (4000)
-- Insert statements for procedure here
set @select = 'select *'
set @from = 'from permohonan'
set @where= 'where idpermohonan= '+@id
set @final=@select+@from+@where
execute (@final)
END

输入参数并执行该SP后,结果为

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.

你能解决这个问题吗?感谢

1 个答案:

答案 0 :(得分:2)

您需要添加空格:

set @select = 'select * '
set @from = 'from permohonan '
set @where= 'where idpermohonan= '+@id

因为没有它你会得到:

select *from permohonanwhere idpermohonan= ...

您应该始终检查您的查询:

IF @debug = 1 
  PRINT @select+@from+@where;

但是对于completness,你不应该连接字符串并使用参数化sp_executesql

ALTER PROCEDURE [dbo].[sinau]   
    @id varchar(MAX)
AS
BEGIN

  SET NOCOUNT ON;

DECLARE @query NVARCHAR(MAX);

SET @query = 
N'SELECT *
  FROM permohonan
  WHERE idpermohonan = @id;';

EXEC [dbo].[sp_executesql]
     @query,
     N'@id VARCHAR(MAX)',
     @id;
END

使用动态SQL可能会非常棘手,因此我强烈建议您阅读 The Curse and Blessings of Dynamic SQL