IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

前端 未结 7 914
旧时难觅i
旧时难觅i 2020-12-12 21:10

How do you say the following in Microsoft SQL Server 2005:

IF EXISTS (SELECT * FROM Table WHERE FieldValue=\'\') THEN
   SELECT TableID FROM Table WHERE Fiel         


        
7条回答
  •  一整个雨季
    2020-12-12 21:43

    IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='') 
    BEGIN
       SELECT TableID FROM Table WHERE FieldValue=''
    END
    ELSE
    BEGIN
       INSERT INTO TABLE(FieldValue) VALUES('')
       SELECT SCOPE_IDENTITY() AS TableID
    END
    

    See here for more information on IF ELSE

    Note: written without a SQL Server install handy to double check this but I think it is correct

    Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column

提交回复
热议问题