Issues with equal sign when assigning statement to # variable for EXEC sp_executesql - sql

Hello: I am trying to encapsulate the following Insert and select statement into a variable for SQL to run.
The issue occurs when the equals sign is included for evaluation (or right around there)
The CustomPollerAssignmentID Column had to be cast since it natively a PK and a uniqueidentifier (see image)
What must be done to have the statement evaluate properly when passes to the sp_executesql?
I receive a syntax error as illustrated below
declare
#date datetime,
#query nvarchar(Max)
set #date = getdate()-4
set #query = --'Insert into [SolarWindsOrion].[dbo].[BWC_VPN_Hourly_Long_Store]
'SELECT * FROM [SolarWindsOrion].[dbo].[CustomPollerStatistics_Hourly]
where Cast(CustomPollerAssignmentID as nvarchar(max)) = 63FEB60-4516-4C1A-9A11-DB30ACA44301'
EXEC sp_executesql #query
UPDATE-->
I tried adding the single quotes.
While the statement does execute.. no results are returned. See Image below

you need to put it in quote like this '63FEB60-4516-4C1A-9A11-DB30ACA44301' , so your adhoc query would look like this :
declare
#date datetime,
#query nvarchar(Max)
set #date = getdate()-4
set #query = --'Insert into [SolarWindsOrion].[dbo].[BWC_VPN_Hourly_Long_Store]
'SELECT * FROM [SolarWindsOrion].[dbo].[CustomPollerStatistics_Hourly]
where Cast(CustomPollerAssignmentID as nvarchar(max)) = ''63FEB60-4516-4C1A-9A11-DB30ACA44301'''
EXEC sp_executesql #query

Related

Problem with a dynamic function in SQL Server

I have a table dbo.t_products and I want to know the last record updated. For that I have an attribute last_changed which stores for each record the timestamp of the last update.
Finally I want to save that result in a variable called #y.
DECLARE #y DATETIME
DECLARE #p_table VARCHAR(100)
SET #p_table = 'dbo.t_products'
EXECUTE sp_executesql N'SET #y = SELECT MAX(last_changed) FROM #p_table'
,N'#p_table VARCHAR, #y DATETIME OUTPUT'
,#p_table
,#y OUTPUT
SELECT #y
The system returns the following message:
Msg 156, Level 15, State 1, Line 25
Incorrect syntax near the keyword 'SELECT'.
Any ideas?
The whole point of using dynamic SQL in your case (I assume) is to allow the use of a dynamic table name. In which case you have to insert the table name into the dynamic SQL string - you can't pass it in as a parameter, thats the problem you are trying in the first place.
Also you don't need a SET followed by a SELECT just use SELECT directly to set the variable.
Finally you definitely want to use the QUOTENAME function to escape your table name and avoid an SQL injection attack - this requires you split the table name and schema name.
DECLARE #y DATETIME;
DECLARE #p_schema VARCHAR(100);
DECLARE #p_table VARCHAR(100);
DECLARE #SQL NVARCHAR(max);
SET #p_schema = 'dbo';
SET #p_table = 't_products';
-- Add the table name to the dynamic SQL
SET #SQL = 'SELECT #y = MAX(last_changed) FROM ' + QUOTENAME(#p_schema) + '.' + QUOTENAME(#p_table);
EXECUTE sp_executesql #SQL, N'#y DATETIME OUTPUT', #y OUTPUT;
-- PRINT(#SQL); --- Debugging
SELECT #y;

Query that saves data in a variable

I am writing an SP in SQL SERVER, and I need one of the steps to execute a query that comes with data from another variable and save that result in another variable for later use in SP. The code I am using displays the following error:
Procedure expects parameter '#handle' of type 'int'.
DECLARE #retorno INT, #sql NVARCHAR(4000), #parametro NVARCHAR(4000), #caminho NVARCHAR(4000)
SET #caminho = '\\arquivos\CÉLULA DE INOVAÇÃO\SQL\19072019.CSV'
SET #parametro = N'#retornoOut INT OUTPUT'
SET #sql = 'SELECT TOP 1 SUBSTRING(RIGHT('''+#caminho+''',12),1,8)'
PRINT #SQL
EXEC sp_execute #sql, #parametro, #retornoOut=#retorno OUTPUT;
The purpose of the code is from a file passed by the user, I can get the name from the given path. I don't know what could be wrong with id.
The problem is that youre using sp_execute , when you should use sp_executesql
this works fine
DECLARE #retorno INT, #sql NVARCHAR(4000), #parametro NVARCHAR(4000), #caminho NVARCHAR(4000)
SET #caminho = '\\arquivos\CÉLULA DE INOVAÇÃO\SQL\19072019.CSV'
SET #parametro = N'#retornoOut INT OUTPUT'
SET #sql = 'SELECT TOP 1 SUBSTRING(RIGHT('''+#caminho+''',12),1,8)'
PRINT #SQL
EXEC sp_executesql #sql, #parametro, #retornoOut=#retorno OUTPUT;
You don't need to use dynamic SQL for this. You can just use set or a simple select:
Using set:
SET #retorno = SUBSTRING(RIGHT(#caminho,12),1,8)
Using select:
SELECT #retorno = SUBSTRING(RIGHT(#caminho,12),1,8)

Using a String to retrieve a column from a function

I am new to SQL and trying to assign value to a variable from the value returned by a function but I am unable to get the value.
My query is :
DECLARE #StartDate DATETIME,#ReferenceDateString VARCHAR(10)='Q1_CY' ;
Select #StartDate=#ReferenceDateString from dbo.Dates(GETDATE());
When I run the above query I just get the value Q1_CY assgined to #StartDate rather than the actual value from the function.
If I don't want to use a variable then my query looks like:
Select #StartDate=Q1_CY from dbo.Dates(GETDATE());
Is there a way to do it ?
It is rather cumbersome in dynamic SQL because you need an output parameter:
declare #StartDate DATETIME,
#ReferenceDateString VARCHAR(10)='Q1_CY' ;
declare #sql nvarchar(max);
set #sql = 'Select #StartDate = #ReferenceDateString from dbo.Dates(GETDATE())';
set #sql = replace(#sql, '#ReferenceDateString', #ReferenceDateString);
exec sp_executesql #sql, N'#StartDate datetime output', #StartDate=#StartDate;

Execute sp_executesql, Table Variabe not Declared

I am Using SQL server 2012 and i want to select random columns from my table by applying where condition in this query:
EXECUTE sp_executesql
N'SELECT *
FROM #table
WHERE #Col = #Value',
N'#Value nvarchar(44),#table nvarchar(55),#Col nvarchar(30)',
#Value = 'Cus_1',#Col='CustId',#table='SaleOrder';
But when I execute it, it shows error
Must declare the table variable "#table"
I also tried it to declare by this: #table table(Id nvarchar(30)), but thin it shows again an error on table type...
Please help
This is what you are trying to run:
EXECUTE sp_executesql
N'SELECT * FROM #table WHERE #Col = #Value',
N'#Value nvarchar(44), #table nvarchar(55), #Col nvarchar(30)',
#Value = 'Cus_1', #Col='CustId', #table='SaleOrder';
Alas. You cannot substitute in a table name or column name using parameter substitution. So, SQL Server is looking for a table variable called #table. You can fix this by putting the values directly into the string:
declare #Col = 'CustId', #table = 'SaleOrder';
declare #sql nvarchar(max) = N'SELECT * FROM ' + #table + ' WHERE ' + #Col + ' = #Value';
EXECUTE sp_executesql #sql,
N'#Value nvarchar(44)',
#Value = 'Cus_1';
Unfortunately, I cannot find a good reference in the documentation that explains what is happening. When a statement is compiled, it is allowed to have parameters. However, the parameters are for values in the statement, not for column, table, database, or UDF names or for keywords. The statement itself is compiled, with place holders for the parameters, and in order to be compiled, the SQL engine needs to resolve all object names.

Specifying Column Name As A Parameter in SELECT statement?

I need to do something like this, but it always fails with 'Error converting data type varchar to int':
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
SET #intParam = SELECT #ColName FROM myTable
How do I accomplish something like this? I can see the problem is that the SELECT statement simply returns the column name as a string, but I am not sure how to fix that. I am using SQL Server 2008R2.
You need to use dynamic sql:
build your dynamic SQL query (take a look at #SQL variable in sample below)
use output parameter to get value back from dynamic sql (take a look at #intParam and #intParam_out in sample below)
execute dynamic sql using sp_executesql
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT #intParam_out = ' + #ColName + ' FROM myTable'
exec sp_executesql #SQL, N'#intParam_out int OUTPUT', #intParam_out = #intParam OUTPUT
Use Cast:
SET #intParam = SELECT cast(#ColName as int) FROM myTable