SQL架构创建失败

时间:2013-08-08 08:50:26

标签: sql sql-server-2008 stored-procedures

从我的db脚本执行以下语句时出现错误。

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PROJ_GetQuestions]') AND type in (N'P', N'PC'))
BEGIN
EXEC('
CREATE PROCEDURE [dbo].[PROJ_GetQuestions]
              (
                    @TestID INTEGER   
              )
              AS            
            SELECT  b.* FROM [IER_TestsCatalogue] a 
            INNER JOIN [IER_QuestionsCatalogue] b 
            ON ',' + a.Selected_CategoryIds + ',' LIKE '%,' + CAST(Category_Id AS VARCHAR(10)) + ',%' 
            WHERE   a.Test_Id = @TestID Order by NEWID()            
      RETURN
')
END

执行上述语句后出错。

Schema Creation Failed: Incorrect syntax near '%'.

1 个答案:

答案 0 :(得分:1)

您可以使用exec更简单alter procedure来完成此操作,例如:

if not exists (select * from sys.procedures where name = 'PROJ_GetQuestions')
    exec ('create procedure dbo.PROJ_GetQuestions as select 1')
go
alter procedure dbo.PROJ_GetQuestions(
    @TestID int)
as
    ... body of stored procedure ...
go

如果你必须使用create procedure编写,这里是一个带有正确引用转义的版本:

EXEC('
CREATE PROCEDURE [dbo].[PROJ_GetQuestions]
              (
                    @TestID INTEGER   
              )
              AS            
            SELECT  b.* FROM [IER_TestsCatalogue] a 
            INNER JOIN [IER_QuestionsCatalogue] b 
            ON '','' + a.Selected_CategoryIds + '','' LIKE ''%,'' +
                CAST(Category_Id AS VARCHAR(10)) + '',%'' 
            WHERE   a.Test_Id = @TestID Order by NEWID()            
      RETURN
')