Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 212
Robert Avatar asked Feb 16 '23 02:02

Robert


1 Answers

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 + '%'
like image 167
marc_s Avatar answered Feb 17 '23 16:02

marc_s