我有以下将更新,插入或删除的存储过程。 从来没有输入DELETE部分的问题。如果我只使用删除部分工作正常,但添加了一个' IF'在它之前阻塞并且永远不会触发代码。 这是SQL Server 2005.存储过程代码:
ALTER PROCEDURE phyadmSetNumbers
@OfficeID int,
@Number varchar(50),
@NumberTypeID int
AS
BEGIN
DECLARE @NumberID int
EXEC phyadmGetNumberID @OfficeID, @NumberTypeID, @NumberID output
IF ((LEN(@Number) > 0) AND (@@RowCount = 1))
BEGIN
UPDATE Number
SET Number = @Number, LastUpdate = GetDate()
WHERE ID = @NumberID
END
ELSE IF ((LEN(@Number) > 0) AND (@@RowCount = 0))
BEGIN
EXEC phyadmInsNumber @OfficeID, @Number, @NumberTypeID
END
ELSE IF (((LEN(@Number) = 0) OR @Number IS NULL) AND (@@RowCount = 1))
BEGIN
SELECT 'In delete if statement'
SELECT 'NumberID is ' + @NumberID
DELETE FROM Number
WHERE ID = @NumberID
select * from Number where ID = @NumberID
DELETE FROM OfficeNumber
WHERE OfficeID = @OfficeID AND NumberID = @NumberID
select * from OfficeNumber WHERE OfficeID = @OfficeID AND NumberID = @NumberID
END
END
如果我评论前2' IF'声明只运行最后,它工作正常。如下所示: 如果它是唯一的' IF'块。
IF (((LEN(@Number) = 0) OR @Number IS NULL) AND (@@RowCount = 1))
BEGIN
SELECT 'In delete if statement'
SELECT 'NumberID is ' + @NumberID
DELETE FROM Number
WHERE ID = @NumberID
select * from Number where ID = @NumberID
DELETE FROM OfficeNumber
WHERE OfficeID = @OfficeID AND NumberID = @NumberID
select * from OfficeNumber WHERE OfficeID = @OfficeID AND NumberID = @NumberID
如果......如果在SQL中使用? 上面的代码有什么问题? 感谢。
更新 接受建议......这是我的新代码:
DECLARE @NumberID int
EXEC phyadmGetNumberID @OfficeID, @NumberTypeID, @NumberID output
IF (@@RowCount = 1)
BEGIN
IF (LEN(@Number) > 0)
BEGIN
UPDATE Number
SET Number = @Number, LastUpdate = GetDate()
WHERE ID = @NumberID
END
ELSE
BEGIN
DELETE FROM Number
WHERE ID = @NumberID
DELETE FROM OfficeNumber
WHERE OfficeID = @OfficeID AND NumberID = @NumberID
END
END
ELSE
BEGIN
EXEC phyadmInsNumber @OfficeID, @Number, @NumberTypeID
END
答案 0 :(得分:3)
If (1=0)
BEGIN
SELECT [col] FROM [table]
END
ELSE
BEGIN
IF (1=1)
BEGIN
SELECT * FROM [table]
END
END
您希望将它们分开并嵌套IF ... ELSE
语句。
答案 1 :(得分:0)
这里的问题是在落入其他地方之前满足条件。正如Ejesalva所说,你需要将它们分开,所以我认为最后的陈述应该是其他的:
ALTER PROCEDURE phyadmSetNumbers
@OfficeID int,
@Number varchar(50),
@NumberTypeID int
AS
BEGIN
DECLARE @NumberID int
EXEC phyadmGetNumberID @OfficeID, @NumberTypeID, @NumberID output
IF ((LEN(@Number) > 0) AND (@@RowCount = 1))
BEGIN
UPDATE Number
SET Number = @Number, LastUpdate = GetDate()
WHERE ID = @NumberID
END
ELSE IF ((LEN(@Number) > 0) AND (@@RowCount = 0))
BEGIN
EXEC phyadmInsNumber @OfficeID, @Number, @NumberTypeID
END
ELSE
BEGIN
SELECT 'In delete if statement'
SELECT 'NumberID is ' + @NumberID
DELETE FROM Number
WHERE ID = @NumberID
select * from Number where ID = @NumberID
DELETE FROM OfficeNumber
WHERE OfficeID = @OfficeID AND NumberID = @NumberID
select * from OfficeNumber WHERE OfficeID = @OfficeID AND NumberID = @NumberID
END
END
我希望这是有道理的