Reputation: 1593
In Azure Data Studio (ADS), is it possible to reuse SQL parameters from query to query? Not sure if I'm jumping out of the intended purpose of ADS but it would be really great if I could declare a set of variables in one code text (or anywhere) and have all my queries understand and utilize them. Something similar to Jupyter notebooks with Python, how you could do the global variables in one code block and all others would respect those variables.
In general, I am having little luck finding documentation on ADS other than the official Microsoft docs.
Upvotes: 15
Views: 7730
Reputation: 3
Yes, you can define also sql statement as a variable and build it first, then execute it:
DECLARE @TableName NVARCHAR(50) = 'Employees';
DECLARE @ColumnName NVARCHAR(50) = 'FirstName';
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = N'SELECT ' + QUOTENAME(@ColumnName) + ' FROM ' + QUOTENAME(@TableName);
EXEC sp_executesql @SQL;
I just needed the same feature and have tested it with Azure Data Studio.
Upvotes: 0
Reputation: 16431
There is no way to declare a global variable in Transact-SQL. So We also can not set global variables with ADS.
In earlier version:
Reference: Variables (Transact-SQL).
But there is another way can help you set the variable as the global variables with SSMS SQLCMD Mode.
You can reference this blog:how to declare global variable in SQL Server..?
Hope this helps.
Upvotes: 2
Reputation: 8324
As far as I know, no, because variables are in the scope of the current batch.
A workaround would be to create a temp table and insert that value. It's really gross, but it works.
In code cell #1:
CREATE TABLE #variableStorage (varname VARCHAR(100), val VARCHAR(100))
INSERT INTO #variableStorage
VALUES
('SomeVariable', 'Foo')
CREATE TABLE #testing (ID INT, testval VARCHAR(100))
INSERT INTO #testing
VALUES
(100, 'Foo')
In code cell #2:
SELECT *
from #testing
WHERE testval = (
SELECT val
FROM #variableStorage
WHERE varname = 'SomeVariable'
)
Upvotes: 7