在SQL查询中使用NOT EXISTS?

时间:2013-06-05 20:55:44

标签: sql sql-server-2008-r2

我的存储过程有问题。我试图通过使用userID & GroupName来查看该组是否不存在我希望能够拥有相同的组用户并且可以为不同的用户设置相同的组名

ALTER PROCEDURE [dbo].[Insert_Group]
   @UserID uniqueidentifier 
   ,@GroupName varchar(100)
   ,@OutGroupID int out 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    if not EXISTS(select Groups.id from Groups where Groups.name = @GroupName and Groups.userID = userID)
    begin 
       -- Insert statements for procedure here
       INSERT INTO [ideaPark_DB].[dbo].[Groups]([userID], [name])
       VALUES (@UserID, @GroupName)

       SELECT @OutGroupID = SCOPE_IDENTITY();
    end 
 else 
    SELECT @OutGroupID = (select Groups.id 
                          from Groups 
                          where Groups.name = @GroupName and Groups.userID = userID)
END

1 个答案:

答案 0 :(得分:0)

我不太确定问题是什么,但看起来您需要在if not exists行添加@:

if not EXISTS(select Groups.id from Groups where Groups.name =@GroupName  and Groups.userID = @userID)

编辑:实际上看起来你也错过了底部的一个。

SELECT @OutGroupID = (select Groups.id 
                      from Groups 
                      where Groups.name = @GroupName and Groups.userID = @userID)