If Exists condition errors out

Ludmil G 101 Reputation points
2023-09-29T16:10:04.6633333+00:00

I am using a cursor and I am trying to check if the record exists and assign it to a variable at the same time , but for some reason it is erroring out. -Incorect sintaxsis near '='

IF EXISTS( SELECT TOP 1 @Event=[se.EventTest] FROM Test)

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,363 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 107.2K Reputation points
    2023-09-29T16:21:45.45+00:00

    You cannot do variable assignment in IF EXISTS. You could do this:

    SELECT @event = NULL
    SELECT TOP 1 @event = "se.EventTest" FROM Test
    IF @event IS NOT NULL
    BEGIN 
       ...
    
    
    

    Note that you need to set the variable to NULL before the assignment, because if SELECT does not hit any rows, @event will retain it's value and will not be set to NULL.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful