1

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

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 '%'.
4

1 回答 1

1

您可以使用更简单的execusing来做到这一点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
')
于 2013-08-08T08:56:50.430 回答