Stuck on SQL Server procedure code
Clash Royale CLAN TAG#URR8PPP
Stuck on SQL Server procedure code
I'm getting an error from this code
DECLARE @existingEmail AS INT
SET NOCOUNT ON;
@existingEmail = COUNT(*) AS total FROM table WHERE email = @email;
INSERT INTO table2 (email)
VALUES (CASE WHEN @existingEmail IS 1 THEN 'Yes' ELSE 'No' END);
That is the error I am getting
Msg 102, Level 15, State 1, Procedure sp_counts, Line 21 [Batch Start Line 7]
Incorrect syntax near '@existingEmail'.
insert
update
@existingEmail = COUNT(*) AS total FROM table WHERE email = @email;
Where's the word SELECT
??– Eric
Aug 8 at 18:37
@existingEmail = COUNT(*) AS total FROM table WHERE email = @email;
SELECT
3 Answers
3
Using COUNT
to check existence may not be best idea from performance point of view:
COUNT
INSERT INTO table2 (email)
SELECT CASE WHEN EXISTS (SELECT 1 FROM table WHERE email = @email) THEN 'Yes'
ELSE 'No' END
Instead of this:
@existingEmail = COUNT(*) as total from table where email = @email;
You need to do this:
SELECT @existingEmail = COUNT(*) as total from table where email = @email;
or this:
SET @existingEmail = (SELECT COUNT(*) as total from table where email = @email);
after using set or select, I am still getting an error:
Msg 156, Level 15, State 1, Procedure sp_counts, Line 21 [Batch Start Line 7] Incorrect syntax near the keyword 'from'. Msg 102, Level 15, State 1, Procedure sp_counts, Line 25 [Batch Start Line 7] Incorrect syntax near '1'.
– JDOB
Aug 8 at 18:21
Msg 156, Level 15, State 1, Procedure sp_counts, Line 21 [Batch Start Line 7] Incorrect syntax near the keyword 'from'. Msg 102, Level 15, State 1, Procedure sp_counts, Line 25 [Batch Start Line 7] Incorrect syntax near '1'.
I don't see anything wrong near the
FROM
in the code you posted, so probably you obfuscated it. As for the 1
you should be using = 1
instead of IS 1
.– Tab Alleman
Aug 8 at 18:24
FROM
1
= 1
IS 1
On the line where you are trying to set your variable @existingEmail
you are missing the key word set
. if you update that line to the following this should resolve that error.
@existingEmail
set
set @existingEmail = (SELECT COUNT(*) from table where email = @email);
this would be a much better answer if you could elaborate on why you proposed this as the solution and what it is doing. not a just code answer
– workabyte
Aug 8 at 19:18
I felt there was no need to elaborate,since the other comments covered the "why" of it.
– user1443098
Aug 8 at 19:36
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Do you really want to
insert
a new row orupdate
an existing row?– Aaron Dietz
Aug 8 at 18:20