patternMajor
Why can't I use variables in T-SQL like I imagine I can?
Viewed 0 times
whycansqllikeimaginevariablesuse
Problem
Forgive me, I am a developer who has moved over to the world of SQL. I thought I could improve some SQL by adding variables but it did not function like I expected. Can someone tell me why this does not work? I don't want a work around, I want to know the reasons why this doesn't work like I imagine it should as I am sure there is a good reason, but currently it doesn't jump out at me.
DECLARE @DatabaseName varchar(150)
SET @DatabaseName = 'MyAmazingDatabaseName'
CREATE DATABASE @DatabaseName
GO
USE @DatabaseName
GOSolution
Per the Books online page for variables
Variables can be used only in expressions, not in place of object
names or keywords. To construct dynamic SQL statements, use EXECUTE.
It would work the way you were expecting if, for example, you used your variable in a where clause. As for why, I would think it has something to do with the parser not able to evaluate the variable and thus check for existence. When executing, the query is parsed first for syntax and objects and then, if parsing successful, the query executes at which point the variable would be set.
Variables can be used only in expressions, not in place of object
names or keywords. To construct dynamic SQL statements, use EXECUTE.
It would work the way you were expecting if, for example, you used your variable in a where clause. As for why, I would think it has something to do with the parser not able to evaluate the variable and thus check for existence. When executing, the query is parsed first for syntax and objects and then, if parsing successful, the query executes at which point the variable would be set.
DECLARE @name varchar(20);
SET @name = 'test';
CREATE TABLE [#tmp]([val] varchar(10));
insert into #tmp
values('test')
SELECT *
FROM [#tmp]
WHERE [val] = @name;Code Snippets
DECLARE @name varchar(20);
SET @name = 'test';
CREATE TABLE [#tmp]([val] varchar(10));
insert into #tmp
values('test')
SELECT *
FROM [#tmp]
WHERE [val] = @name;Context
StackExchange Database Administrators Q#157912, answer score: 21
Revisions (0)
No revisions yet.