2015-11-06 27 views
1

简单的问题,但浪费时间寻找答案。我已经存储了这样的在局部变量存储过程中输入等于(=)

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= '[email protected] 
set @[email protected][email protected][email protected] 
execute (@final) 
END 

程序后,我的输入参数和exec是SP,结果是

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

你能解决这个问题?由于

+1

使用参数化查询。搜索'sp_executesql'并按照教程。 – MatBailie

+0

为什么定义3个不同的变量,而您只能使用一个:'set @final ='select * from permohonan where idpermohonan ='+ @ id'? – MusicLovingIndianGirl

+2

'set @select ='select *' set @from ='from permohonan' set @ where ='where idpermohonan ='+ @ id'。 **添加空格**无论如何,写这样的代码是混乱的。您应该真的使用参数化的'sp_executesql' – lad2025

回答

2

您需要添加空格:

set @select = 'select * ' 
set @from = 'from permohonan ' 
set @where= 'where idpermohonan= '[email protected] 

,因为没有它,你得到:

select *from permohonanwhere idpermohonan= ... 

您应经常检查您的查询:

IF @debug = 1 
    PRINT @[email protected][email protected]; 

但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