I’m trying to write a script in T-SQL to resolve a critical issue on our system. Unfortunately I have never done this before so I’m entering uncharted waters.
I’m actually writing a PHP script to generate this SQL. If the user exists, create it. But in both cases, add the user to a group.
DECLARE @userId AS int
/* --------------- 123l123123fvsdf - Name --------------- */
BEGIN
IF EXISTS(SELECT id FROM [CMT_UAT].[dbo].[user] WHERE username = '123l123123fvsdf')
INSERT INTO [CMT_UAT].[dbo].[user](username, password, email, firstname, lastname, created) VALUES('123l123123fvsdf', 'PASSWORD', 'aa00043@user.com', 'firstName', 'lastName', GETDATE())
GO
SET @userId = @@IDENTITY
ELSE
SET @userId = SELECT id FROM [CMT_UAT].[dbo].[user] WHERE username = 'AA00043'
END
INSERT INTO [CMT_UAT].[dbo].[user_group](user_id, group_id) VALUES(@userId, '7')
I’m getting these errors:
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ‘)’.
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable “@userId”.
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword ‘SELECT’.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword ‘INSERT’.
Msg 137, Level 15, State 2, Line 5
Must declare the scalar variable “@userId”.
I’ve done some googling on the scalar value and it can happen when my query returns multiple rows, which I’ve verified that it doesn’t.
you need to fix your if statement. try:
you have multipl statements in the first part of your if block but you forgot to put
BEGINandENDaround itAnd also like RBarryYoung pointed out you need to take the
GOout