SQL Azure Data warehouse Dynamic SQL Select query - azure-sql-database

In Azure SQL Data Warehouse stored procedure I try to form Dynamic SQL and perform select query,I unable to fetch the resutSet
Below is code Snippet:
DECLARE #sql nvarchar(400)
DECLARE #cnt int
BEGIN
---Some Business Logic---
SELECT #sql = N'select #cnt = count(*) from '+quotename(#src_TableName)+' where warn_remarks like ''%'+ #condition +'%''';
SET #parameter = N'#cnt int OUTPUT'
EXECUTE sp_executesql #sql,#parameter,#cnt = #cnt OUTPUT
END
The Error it is showing is
"Incorrect syntax near '='",In the select query when assigning count(*) to a variable it is giving error.But the same logic is working fine in Azure SQL Database.Kindly help to solve this.

You'll need to use SET instead, because you can't set variables using SELECT in SQL DW or PDW.
DECLARE #sql nvarchar(400)
DECLARE #cnt int
BEGIN
---Some Business Logic---
SET #sql = N'SET #cnt = (select count(*) from '+quotename(#src_TableName)+' where warn_remarks like ''%'+ #condition +'%'')'; --replaced
SET #parameter = N'#cnt int OUTPUT'
EXECUTE sp_executesql #sql,#parameter,#cnt = #cnt OUTPUT
END

Select #var is not supported in Azure SQL data warehouse.
https://msdn.microsoft.com/en-us/library/ms187330.aspx
You can find workarounds https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-develop-variable-assignment/

Related

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?

How to pass table name dynamically to the stored procedure or a simple SQL query, then store the results in a variable?
You may looking for something like this ?
USE [master]
GO
DECLARE #sql NVARCHAR(2000)
DECLARE #TableName NVARCHAR(100) ='sys.tables'
DECLARE #RecordCount INT
SET #sql = N' SELECT #RecordCountOut = COUNT(*)
FROM ' + #TableName + ' AS t'
EXEC sp_executesql #sql, N'#RecordCountOut INT OUTPUT', #RecordCountOut = #RecordCount OUTPUT
SELECT #RecordCount
You could stored your SQL query result in this way
DECLARE #Result NVARCHAR(MAX)
SELECT #Result = COLUMN FROM TableName
however, you could use print command to check what the query return
print #Result

Using variables in Transact-sql exists subquery

this seems like it should be extraordinarily simple, so I apologize in advance if this information is easily accessible on the transact-sql documentation pages. I searched myself, but couldn't seem to find anything.
I'm trying to modify a transact-sql statement that currently runs on our Windows server 2000 box. I want to check if a table in another database exists, and then do a bunch of stuff. The database name is given as a string argument, '#dbName'
CREATE PROCEDURE CopyTables
#dbName char(4)
AS
IF EXISTS (SELECT * FROM #dbName.INFORMATION_SCHEMA.TABLES WHERE
TABLE_NAME = N'MainTable')
BEGIN
--Do Stuff
In it's current state, it doesn't like using the bare #dbName variable within the select statement. Is there special syntax for doing this?
Thanks in advance.
The below code should do what you want. As was mentioned previously, the account running the query would need the privilege to query the INFORMATION_SCHEMAs in the target database.
To future-proof your stored procedure, I'd also suggest increasing the length of the database name parameter and declaring it as an nchar or nvarchar in stead of char.
CREATE PROCEDURE CopyTables
#dbName char(4)
AS
DECLARE
#SQLStr nvarchar (max),
#Params nvarchar (max),
#Count tinyint;
SET
#Count = 0;
SET #SQLStr = N'SELECT #qCount = 1 FROM [' + #dbName + N'].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N''MainTable''';
SET #Params = N'#qdbName char (4), #qCount tinyint OUTPUT';
EXECUTE sp_executesql #SQLStr, #Params, #qdbName = #dbName, #qCount = #Count OUTPUT;
IF #Count = 1
BEGIN
--Do Stuff
END; -- if
GO
Try doing the following:
DECLARE #dbName NVARCHAR(MAX) = 'master', #TableName NVARCHAR(MAX) = N'spt_monitor';
DECLARE #sql NVARCHAR(MAX) = N'SELECT * FROM [' + #dbName + N'].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''' + REPLACE(#TableName,N'''',N'''''') + N'''';
SET NOCOUNT OFF;
EXEC(#sql);
IF ##ROWCOUNT > 0 BEGIN;
-- DO STUFF
SELECT NULL;
END;
There are a few shortcomings to this solution:
1) It requires that the user executing the statement has SELECT access to the other database's INFORMATION_SCHEMA.TABLES
2) It has the side-effect of actually selecting the rows, so if you're using a reader to access the results, you'll have to call reader.NextResult() or await reader.NextResultAsync() because it actually outputs the results of the SELECT statement, rather than doing it in an IF EXISTS context.
By merging the two solutions, we get this:
DECLARE #dbName NVARCHAR(MAX) = 'master', #TableName NVARCHAR(MAX) = N'spt_monitor';
DECLARE #sql NVARCHAR(MAX) = N'SELECT #count = COUNT(*) FROM [' + #dbName + N'].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''' + REPLACE(#TableName,N'''',N'''''') + N'''';
DECLARE #Count INT;
EXECUTE sp_executesql #sql, N'#Count INT OUTPUT', #Count OUTPUT;
IF #Count > 0 BEGIN;
-- Do stuff
SELECT 'the table exists';
END ELSE BEGIN;
-- Do stuff
SELECT 'the table does not exist';
END;
This solution requires that the user executing the statement has SELECT access to the other database's INFORMATION_SCHEMA.TABLES, but it does not have the side-effect of selecting rows, like my previous solution.

SELECT FROM #random_table SQL Server 2008 R2

I'm having an issue with the following code:
DECLARE #table varchar(50), #value int
SET #table = 'randomTable'
EXEC('SELECT #value = exercicio FROM '+#table+' WHERE cod = 2')
I need to do a couple of operations like that one above in some random tables. I want to select a value and store in a variable previously declared. But when I tried to execute that code, I received the following message:
Must declare the scalar variable "#value".
I'm out of ideas. Any suggestions?
The #value variable is outside the scope of the dynamic SQL statement. You'll need to return the value as an output parameter:
DECLARE
#table nvarchar(251) = N'dbo.randomTable'
, #SQL nvarchar(MAX)
, #value int;
SET #SQL = N'SELECT #value = exercicio FROM '+#table+N' WHERE cod=2';
EXEC sp_executesql #SQL, N'#value int OUTPUT', #value OUT;

Build select statement dynamically and use it to populate a stored procedure variable

I am trying to get count of a rows with specific values in a table, and if the count is 0, then add a value in the table. This count is a local variable in stored procedure.
I am building the SQL dynamically and storing SQL statement into a nvarchar variable.
Then, using EXEC I am running this SQL as follows hoping to populate count variable.
But it's not working.
DECLARE #qry NVARCHAR(max)
DECLARE #count INT
-- building #qry will result as follows
#qry = SELECT #count = COUNT(*) FROM aTable WHERE (col1 = #col1 AND ...)
#count = EXEC #qry
IF #count = 0
BEGIN
-- carry on with adding
END
In your sql ,why you are execute your query through EXEC because of your required output is already in #count variable so it is not need in your case.
Please refer below syntax.
DECLARE #qry Numeric
DECLARE #count INT
-- building #qry will result as follows
SELECT #count = COUNT(*) FROM aTable WHERE (col1 = #col1 AND ...)
IF #count = 0
BEGIN
-- carry on with adding
END
If you are building the query dynamically, you need sp_executesql. Try something like
-- building #qry will result as follows
#qry = 'SELECT #count = COUNT(*) FROM aTable WHERE (col1 = #col1 AND ...)'
EXEC sp_executesql #qry, N'#count INT OUTPUT', #count OUTPUT;
--Do whatever you want with #count...
Source: Aaron Bertrand's answer here and sp_executesql explanation..
I think #qry needs to be a string for executing, not the result of the select, like so:
DECLARE #qry NVARCHAR(max);
DECLARE #count INT;
-- building #qry will result as follows
SET #qry = 'SELECT COUNT(*) FROM aTable WHERE (col1 = #col1 AND ...)';
SET #count = exec #qry;

Assign db query value to t-sql variable in dynamic query

I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that.
This is the stored procedure that i am working on . This is throwing some errors as i don't think there is a simple way of assigning the result of a tsql dynamic query to a variable.
CREATE PROCEDURE test
AS
BEGIN
DECLARE #sql VARCHAR(255)
DECLARE #cnt int
SET #sql = 'SELECT COUNT(1) FROM myTable'
SET #cnt = EXEC(#sql)
IF (#cnt > 0)
PRINT 'A'
ELSE
PRINT 'B'
END
GO
Could someone tell me if there is a simpler way of achieving this using T-SQL ?
Thanks.
alternative:
declare #tablename varchar(512) = 'sometable'
declare #sql nvarchar(512) = 'set #count = (select count(*) from ' + #tablename + ')'
declare #count int
execute sp_executesql #sql, N'#count int output', #count=#count output
select case when #count > 0 then 'A' else 'B' end
Try this:
SET #sql = 'SELECT #cnt = COUNT(1) FROM myTable'
EXEC(#sql)