0

i am trying to to something like if my database dont have the record, then insert it, the query below is my checking, the code have no errors, so i am not sure did i really make the checking ?

Record 1

IF NOT EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 1 )
INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
VALUES (1,'User','UserInfo')

Record 2

IF NOT EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 2 )
INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
VALUES (2,'User2','UserInfo2')
4

1 回答 1

0

如果您只想获取某种类型的返回值,请使用函数或存储过程并返回一个值。例如,

IF EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 1 )
   Return -1
Else
   INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
   VALUES (1,'User','UserInfo')

IF EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 2 )
   Return -2
Else
   INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
   VALUES (2,'User2','UserInfo2')

如果仅使用临时查询或 SSMS 中的查询窗口,请在其上方创建一个变量或仅打印消息。如果将变量与编码的 sql 查询一起使用,则可以取回返回值。

Declare @ErrorValues int;
Select @ErrorValues = 0;

IF EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 1 )
 BEGIN
   Select @ErrorValues = @ErrorValues - 1;
   PRINT '-1';
Else
   INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
   VALUES (1,'User','UserInfo')

IF EXISTS ( SELECT 1 FROM TBL_AUDIT_LOG_TYPE WHERE AUDIT_LOG_TYPE_ID = 2 )
 BEGIN
   Select @ErrorValues = @ErrorValues - 2;
   Print '-2'; --or PRINT 'audit_log_type_ID of 2 already exists';
 END
Else
   INSERT INTO TBL_AUDIT_LOG_TYPE ([AUDIT_LOG_TYPE_ID],[MODULE],[ACTION]) 
   VALUES (2,'User2','UserInfo2')
于 2013-04-24T05:54:38.737 回答