0

我有一个问题,我似乎没有得到解决。如果我从完整代码中删除以下部分,则存储过程在创建时会引发错误:

-- SET @ResultType = 'Success'
-- SET @ResultMessage = 'Environment Created'

我该如何解决这个问题?

CREATE PROC [dbo].[usp_InsertEnvironment] 
    @EnvironmentName nvarchar(50),
    @EnvironmentDescription nvarchar(250),
    @ResultType as Nvarchar(50) OUTPUT,
    @ResultMessage as Nvarchar(250) OUTPUT

AS 
    --SET NOCOUNT ON 
    --SET XACT_ABORT ON  

BEGIN TRANSACTION

    IF  NOT EXISTS(SELECT * FROM dbo.Environment WHERE EnvironmentName = @EnvironmentName)
        --This environmentName does not exists, so insert...
        INSERT INTO dbo.Environment 
        SELECT  @EnvironmentName, @EnvironmentDescription

            -- I get an error if I decomment the 2 lines underneath :-(
        --SET @ResultType = 'Success'
        --SET @ResultMessage = 'Environment Created'

    ELSE
        --This environmentName does not exists so throw error

        SET @ResultType = 'Error'
        SET @ResultMessage = 'Environment already exists'

COMMIT
4

1 回答 1

2

更改代码以使用 BEGIN...END 块。

IF...ELSE (Transact-SQL)

IF Boolean_expression 
     { sql_statement | statement_block } 
[ ELSE 
     { sql_statement | statement_block } ] 

Boolean_expression
是返回 TRUE 或 FALSE 的表达式。如果布尔表达式包含 SELECT 语句,则 SELECT 语句必须用括号括起来。

{ sql_statement| 语句块}

是使用语句块定义的任何 Transact-SQL 语句或语句分组。除非使用语句块,否则 IF 或 ELSE 条件只能影响一个 Transact-SQL 语句的性能。

要定义语句块,请使用流控制关键字 BEGIN 和 END。

就像是

BEGIN TRANSACTION

    IF  NOT EXISTS(SELECT * FROM dbo.Environment WHERE EnvironmentName = @EnvironmentName)
    BEGIN
        --This environmentName does not exists, so insert...
        INSERT INTO dbo.Environment 
        SELECT  @EnvironmentName, @EnvironmentDescription

            -- I get an error if I decomment the 2 lines underneath :-(
        --SET @ResultType = 'Success'
        --SET @ResultMessage = 'Environment Created'
    END
    ELSE
    BEGIN
        --This environmentName does not exists so throw error

        SET @ResultType = 'Error'
        SET @ResultMessage = 'Environment already exists'
    END

COMMIT
于 2013-08-14T11:50:18.417 回答