1
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 都被打印出来了

有人可以帮我修复错误吗

4

1 回答 1

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
于 2013-11-05T23:33:40.730 回答