Passing variables to SQL string

Can someone help me with the attached syntax

DECLARE @SearchString NVARCHAR(MAX)
SET     @SearchString = 'fletc'

USE [Prodution]
GO

SELECT * FROM [User] WHERE Username LIKE '%' + @SearchString + '%'

I am trying to combine the LIKE statement below. However, I get the error message:

Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@SearchString".

Any help would be greatly appreciated.

thanks

Rob

+4
source share
2 answers

Using GOcompletes the scope (so that all variables declared before it are "lost") - move the declaration in after GO :

USE [Production]
GO

DECLARE @SearchString NVARCHAR(MAX)
SET     @SearchString = 'fletc'

SELECT * FROM [User] WHERE Username LIKE '%' + @SearchString + '%'
+6
source

In your code:

DECLARE @SearchString NVARCHAR(MAX)
SET     @SearchString = 'fletc'

USE [Prodution]
GO

SELECT * FROM [User] WHERE Username LIKE '%' + @SearchString + '%'

There is a GO instruction. Visibility starts again after GO

+1
source

All Articles