我试图将IF / ELSE语句放入存储过程。
CREATE PROCEDURE [dbo].[Sp_enty_srch_attr_vals]
(@ENTY_ID INT,
@FIELD_ID INT,
@VALUE VARCHAR(5000),
@SQL VARCHAR(5000)
)
AS
BEGIN
IF (@FIELD_ID = 148)
SET nocount ON;
SET @SQL = 'SELECT DISTINCT [GPI] FROM [GPI_ASOC] WHERE [GPI] LIKE ''%@VALUE%'' ORDER BY GPI';
SET @SQL = replace(@SQL, '@VALUE', @VALUE);
EXEC SP_EXECUTESQL @SQL;
ELSE
SET nocount ON;
DECLARE @ENTY_TABLE_NAME VARCHAR(500)
SET @ENTY_TABLE_NAME = (SELECT TOP 1 enty_table_name
FROM enty
WHERE enty.enty_id = @ENTY_ID)
EXEC( 'SELECT DISTINCT ATTR_VAL FROM '+@ENTY_TABLE_NAME+'_ATTR WHERE FIELD_ID='+@FIELD_ID+
' AND ATTR_VAL LIKE ''%'+@VALUE+'%'' ORDER BY ATTR_VAL ' )
END
我收到了这个错误,我一直在试图解决它的问题。
消息156,级别15,状态1,过程Sp_enty_srch_attr_vals,第14行[批次启动第17行]
关键字“ELSE”附近的语法不正确。
这个脚本有什么问题?
答案 0 :(得分:3)
如果IF
条件中有多个语句,则需要使用BEGIN-END
块
If <<condition>>
BEGIN
<<stmt 1>>
<<stmt 2>>
END
ELSE
BEGIN
<<stmt 3>>
<<stmt 4>>
END
也不要将sp_
添加到存储过程的前缀。所有系统存储过程都将以sp_
为前缀。这是关于问题的文章
答案 1 :(得分:1)
您需要BEGIN和END才能将代码包含在IF / ELSE的正文中。您也可以将SET NOCOUNT ON移到IF之外:
CREATE PROCEDURE [dbo].[Enty_srch_attr_vals] (@ENTY_ID INT,
@FIELD_ID INT,
@VALUE VARCHAR(5000),
@SQL VARCHAR(5000))
AS
BEGIN
SET nocount ON;
IF( @FIELD_ID = 148 )
BEGIN
SET @SQL = 'SELECT DISTINCT [GPI] FROM [GPI_ASOC] WHERE [GPI] LIKE ''%@VALUE%'' ORDER BY GPI';
SET @SQL = replace(@SQL, '@VALUE', @VALUE);
EXEC SP_EXECUTESQL @SQL;
END
ELSE
BEGIN
DECLARE @ENTY_TABLE_NAME VARCHAR(500)
SET @ENTY_TABLE_NAME = (SELECT TOP 1 enty_table_name
FROM enty
WHERE enty.enty_id = @ENTY_ID)
EXEC( 'SELECT DISTINCT ATTR_VAL FROM '+@ENTY_TABLE_NAME+'_ATTR WHERE FIELD_ID='+@FIELD_ID+
' AND ATTR_VAL LIKE ''%'+@VALUE+'%'' ORDER BY ATTR_VAL ' )
END
END
go
答案 2 :(得分:1)
对于多行IF / ELSE语句,您应该使用BEGIN / END块,例如
IF( @FIELD_ID = 148 )
BEGIN
SET nocount ON;
SET @SQL = 'SELECT DISTINCT [GPI] FROM [GPI_ASOC] WHERE [GPI] LIKE ''%@VALUE%'' ORDER BY GPI';
SET @SQL = replace(@SQL, '@VALUE', @VALUE);
EXEC SP_EXECUTESQL @SQL;
END