如果Exists()t sql循环问题

时间:2013-11-05 23:29:12

标签: sql-server tsql

DECLARE @tag VARCHAR(MAX)
DECLARE @TagID as INT;
DECLARE @ID as INT;
DECLARE tag_cursor CURSOR
FOR
SELECT tagname FROM #temptag  
 FOR READ ONLY
  OPEN tag_cursor
    FETCH NEXT FROM tag_cursor INTO @tag
       WHILE @@FETCH_STATUS = 0
          BEGIN              

            IF EXISTS (SELECT TOP 1 * FROM Tag WHERE TagName=@tag) 
                   BEGIN
                       print 1;
                   END 
                      print 2;
                      /* INSERT INTO Tag
                       SELECT @tag FROM #temptag 
                       SELECT @TagID = SCOPE_IDENTITY(); 

                       print @TagID*/
                FETCH NEXT FROM tag_cursor INTO @tag
                     END

           CLOSE  tag_cursor   
           DEALLOCATE tag_cursor      

在我的存储过程中,我在表中搜索一个值。如果该值已经存在,那么我不应该插入值。

所以我写了

      IF EXISTS (SELECT TOP 1 * FROM Tag WHERE TagName=@tag) 
               BEGIN
                   print 1;
               END 
                  print 2;
                  /* INSERT INTO Tag
                   SELECT @tag FROM #temptag 
                   SELECT @TagID = SCOPE_IDENTITY(); 

                   print @TagID*/
            FETCH NEXT FROM tag_cursor INTO @tag
                 END

问题:当我运行它时,print1和print 2的值都被打印

有人可以帮我解决错误

1 个答案:

答案 0 :(得分:1)

也许你想要ELSE阻止?

IF EXISTS (SELECT TOP 1 * FROM Tag WHERE TagName=@tag) 
BEGIN
    print 1;
END
ELSE
BEGIN 
    print 2;
    /* INSERT INTO Tag
       SELECT @tag FROM #temptag 
       SELECT @TagID = SCOPE_IDENTITY(); 

       print @TagID*/
END