简体   繁体   中英

Use NOT EXISTS in SQL Query?

I have problem with my stored procedure. I am trying to see if the group does not EXISTS by seeing of by using the userID & GroupName I want to be able could not have same group user and could have same group name for different user

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

I'm not quite sure what the question is, but it looks like you need to add a @ on your if not exists line:

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

Edit: Actually it looks like you are missing one on the bottom too.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM