Your INSERT
statement is malformed; you may want to try something like:
Insert into usergroup (user_id, group_id, default_group)
Select ug.user_id, 1234 AS group_id, ug.default_group
from [user_group] ug
join [group] g on ug.group_id = g.id
where g.name = 'someName';
Replace 1234
in the query above with the id of the group you wish to add for each user who is a member of someName
.
A fully flushed out test script for this, including the NOT EXISTS
clause you referenced:
USE tempdb;
CREATE TABLE dbo.groups
(
GroupID INT CONSTRAINT PK_groups
PRIMARY KEY CLUSTERED IDENTITY(1,1)
, GroupName VARCHAR(255)
);
CREATE TABLE dbo.usergroup
(
UserID int
, GroupID int
CONSTRAINT FK_usergroup_groups__group_id
FOREIGN KEY REFERENCES dbo.groups(GroupID)
, DefaultGroup bit
CONSTRAINT DF_usergroup__default_group DEFAULT ((0))
, CONSTRAINT PK_usergroup PRIMARY KEY CLUSTERED (UserID, GroupID)
);
INSERT INTO dbo.groups (GroupName)
VALUES ('test 1');
INSERT INTO dbo.groups (GroupName)
VALUES ('test 2');
INSERT INTO dbo.usergroup (UserID, GroupID, DefaultGroup)
VALUES (1, 1, 1);
DECLARE @NewGroupID INT;
DECLARE @ExistingGroupName VARCHAR(255);
SET @ExistingGroupName = 'test 1';
SET @NewGroupID = 2;
INSERT INTO dbo.usergroup (UserID, GroupID, DefaultGroup)
SELECT ug.UserID, @NewGroupID AS GroupID, ug.DefaultGroup
FROM dbo.usergroup ug
INNER JOIN dbo.groups g ON ug.GroupID = g.GroupID
WHERE g.GroupName = @ExistingGroupName
AND NOT EXISTS (
SELECT 1
FROM dbo.usergroup ug1
WHERE ug1.UserID = ug.UserID
AND ug1.GroupID = @NewGroupID);
As you may notice in the above code, I've used two-part naming to include the schema name when referencing table names. Also, I've added two variables to the INSERT INTO
portion of code to simplify making changes.
I've added USE tempdb;
- once SQL Server is restarted tempdb is automatically recreated; effectively dropping the tables I create in this code.
I'm also not calling the group table group
, since that is a reserved word. Using it in code will be a recipe for confusing down-the-road. I've named it groups
in my code above, since that more accurately reflects the content of the table.
Also, I've renamed several of your columns to more accurately reflect the content of those columns. For instance, you have an id
column in the group
table. I've renamed it GroupID
, and used that nomenclature everywhere. This simplifies debugging.
usergroup
oruser_group
?