Why this insert is not getting compiled :-
INSERT INTO dbo.UserGroupsToUsers
( UserID ,
LastUpdated ,
ID ,
UserGroupID
)
SELECT @MergeToUserID ,
GETDATE() ,
MAX(ID) + 1 ,
UserGroupID
FROM dbo.UserGroupsToUsers
WHERE UserID = @MergeFromUserID
Error: Column ‘dbo.UserGroupsToUsers.UserGroupID’ is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.
You should make your
IDfield into an IDENTITY (autoincrementing field) and omit it from the query.If you can’t change the database you could try this:
Important note: This assumes that only one row will be returned. The insert will fail by design if your subquery returns more than one row and ID is a primary key or has a unique constraint.