-2

I am trying to do a query, but I keep getting the following error:

Must declare the scalar variable "@userId".

But as you can see from the sql below (simplified example), that variable is declared.

declare @userId uniqueidentifier = '76652631-bd15-22b2-1a00-6ae6ee1e101a'

USE MyDatabase
GO

SELECT * FROM [User] where UserId = @userId

Why is this happening?

JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123

1 Answers1

1

The problem is that that 'GO' statement is a terminator, so after it's executed, the variable (created above it, but used below it) no longer exists.

Change your code to the following and it will work.

USE MyDatabase
GO

declare @userId uniqueidentifier = '76652631-bd15-22b2-1a00-6ae6ee1e101a'

SELECT * FROM [User] where UserId = @userId
JsAndDotNet
  • 16,260
  • 18
  • 100
  • 123