Error 137

Troubleshooting SQL Server

Troubleshooting

Error 137

Severity Level 15
Message Text

Must declare the variable '%.*ls'.

Explanation

This error occurs when a variable is used in a SQL script without first declaring the variable. This example returns error 137:

SET @mycol = 'ContactName'
SELECT @mycol
GO

One of the more complicated causes of this error includes the use of a variable that was declared outside the EXECUTE statement. For example:

USE Northwind
GO
DECLARE @mycol nvarchar(20)
SET @mycol = 'ContactName'
EXECUTE ('SELECT @mycol FROM Customers')
Action

Verify that any variables used in a SQL script are declared before being used elsewhere in the script.

Rewrite the procedure so that it does not reference variables in the EXECUTE statement that were declared outside of it.

USE Northwind
GO
DECLARE @mycol nvarchar(20)
SET @mycol = 'ContactName'
EXECUTE ('SELECT ' + @mycol + ' FROM Customers')

See Also

DECLARE @local_variable

Errors 1 - 999

EXECUTE

SELECT @local_variable

SET @local_variable