If Exists condition errors out

Ludmil G 81 Reputation points

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.
12,892 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 102.3K Reputation points

    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

    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