我有一个问题,我似乎没有得到修复。 如果我从完整代码中取消以下部分,则存储过程在创建时会抛出错误:
-- 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
答案 0 :(得分:2)
更改代码以使用BEGIN ... END块。
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
逻辑表达式
是一个返回TRUE或FALSE的表达式。如果 Boolean表达式包含SELECT语句SELECT 声明必须括在括号中。{sql_statement | statement_block}
是否有任何Transact-SQL语句或 使用语句块定义的语句分组。除非a 使用语句块,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