Robert
Robert

Reputation: 75

Passing Variables into a SQL String

Can someone help me with the syntax attached

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

USE [Prodution]
GO

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

I am trying to concatenate the LIKE statement at the bottom. However, I am getting the error message attached:

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

Any help would be greatly appreciated.

thanks

Rob

Upvotes: 4

Views: 1981

Answers (2)

Joe Taras
Joe Taras

Reputation: 15379

In your code:

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

USE [Prodution]
GO

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

there's a GO statement. Visibility starts again after GO

Upvotes: 1

marc_s
marc_s

Reputation: 754348

The use of GO terminates a scope (so all variables declared before it are "lost") - move your declaration to after the GO:

USE [Production]
GO

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

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

Upvotes: 7

Related Questions