我对t sql的经验很少,我必须写一个存储的。
这是我存储的:
USE myDatabase GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[myStored] ( @myPar1 INT, @myPar2 SMALLDATETIME ) AS BEGIN SET NOCOUNT ON IF EXISTS ( SELECT 1 FROM myTable1 WHERE myPar1 = @myPar1 AND myPar2 = @myPar2 ) BEGIN DELETE FROM myTable1 WHERE myPar1 = @myPar1 AND myPar2 = @myPar2 END ELSE IF EXISTS ( SELECT 1 FROM myTable2 WHERE myPar2 = @myPar2 ) BEGIN INSERT INTO myTable1 (myField1, myField2, myField3, myField4) VALUES (@myPar1, @myPar2, '', 1) END ELSE IF EXISTS ( SELECT 1 FROM myTable3 WHERE myPar2 = @myPar2 ) BEGIN INSERT INTO myTable1 (myField1, myField2, myField3, myField4) VALUES (@myPar1, @myPar2, '', 1) END END
这些是我的问题:
1-是否存在宏观误差?
2-有人建议使用“ SELECT CASE”,其他人建议使用“ IF … ELSE”,有什么区别?那我的存储的最佳选择是什么?
3-我不确定使用“ BEGIN … END”语句,特别是结合使用“ IF … ELSE”语句。这是什么意思?是否有必要在“ IF … ELSE”语句中放入“ BEGIN … END”?还要执行一条指令吗?
对于单个IF语句
IF (Some Condition) --<-- If condition is true control will get inside the BEGIN -- BEGIN ..END Block and execute the Code inisde /* Your Code Here*/ END
所有单个IF语句将独立检查条件。
一击一击
IF (Some Condition) --<-- If condition is true control will get inside the BEGIN -- BEGIN ..END Block and execute the Code inisde /* Your Code Here*/ -- IF not true control will jump to Else block END ELSE --<-- You dont mention any condition here BEGIN /* Your Code Here*/ END
如果IF true,则仅执行一个代码块,然后执行第一个代码块Otherwsie ELSE代码块。
多个IF和ELSE
IF (Some Condition) --<--1) If condition is true control will get inside the BEGIN -- BEGIN ..END Block and execute the Code inisde /* Your Code Here*/ -- IF not true control will check next ELSE IF Blocl END ELSE IF (Some Condition) --<--2) This Condition will be checked BEGIN /* Your Code Here*/ END ELSE IF (Some Condition) --<--3) This Condition will be checked BEGIN /* Your Code Here*/ END ELSE --<-- No condition is given here Executes if non of BEGIN --the previous IFs were true just like a Default value /* Your Code Here*/ END
如果条件为真,则仅执行代码的第一块,其余部分将被忽略。
BEGIN ..END块
在执行任何IF,ELSE IF或ELSE之后,如果要执行多个语句,则必须将它们包装在一个BEGIN..END块中。如果仅执行一条语句,则没有必要,但是始终使用BEGIN END块是一个好习惯,这样可以更轻松地读取您的代码。
BEGIN..END
您的程序
我已经取出ELSE语句来使每个IF语句独立地检查给定条件,现在您已经有了一些有关如何处理IF和ELSE的想法,因此请自己尝试一下,因为我不知道您到底想在此处应用什么逻辑。
CREATE PROCEDURE [dbo].[myStored] ( @myPar1 INT, @myPar2 SMALLDATETIME ) AS BEGIN SET NOCOUNT ON IF EXISTS (SELECT 1 FROM myTable1 WHERE myPar1 = @myPar1 AND myPar2 = @myPar2) BEGIN DELETE FROM myTable1 WHERE myPar1 = @myPar1 AND myPar2 = @myPar2 END IF EXISTS (SELECT 1 FROM myTable2 WHERE myPar2 = @myPar2) BEGIN INSERT INTO myTable1(myField1, myField2, myField3, myField4) VALUES(@myPar1, @myPar2, '', 1) END IF EXISTS (SELECT 1 FROM myTable3 WHERE myPar2 = @myPar2) BEGIN INSERT INTO myTable1(myField1, myField2, myField3, myField4) VALUES(@myPar1, @myPar2, '', 1) END END