2015-11-06 26 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