Concatinate Variable define in Dynamic Query - dynamicquery

I'm building a dynamic query. Inside it, I have declare variables. Now I want to concatenate this variable in my insert query
declare #qry nvarchar(MAX)
select #qry='Declare #var1 nvarchar(10); set #var1 =''abcd''
insert into mytable (col1) values ('+#var1+')'
When I execute this code it give me an error
Must declare the scalar variable "#var1".
But if I declare #var1 outside #qry then it works fine.I am having problem in concatenating the value of variable.
Please help
Thanks

You cannot do that. The context of execution of Dynamic query is different from the outer script.
this will work
declare #qry nvarchar(MAX)
Declare #var1 nvarchar(10);
set #var1 ='abcd'
select #qry='insert into mytable (col1) values ('+#var1+')'

Related

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

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

MS SQL - Variable in a variable

I've been wondering if it's possible to declare and set a variable within the definition of another variable.
For example:
declare #variable varchar(250)
set #variable =
'INSERT INTO [BLAH] (Nope, Hype, Friends)
VALUES (declare #value varchar(250) set #value = 'example' exec #value, #value, #value)'
exec #variable
I'm probably doing multiple really basic mistakes here - just trying to understand as much as fast as possible
it can be done as below.
declare #variable varchar(800)
set #variable =
' declare #value varchar(10) = ''example''
INSERT INTO [BLAH] (Nope, Hype, Friends)
VALUES ( #value, #value, #value)'
exec #variable
Also get a knowledge of SQL injection before you work with dynamic sql.
Yes you can declare a set of variable inside a variable: doing like this.
DECLARE #variable varchar(max)
SET #variable =
'declare #value varchar(max) = ''example''
Insert into BLAH
values(#value,#value)'
EXEC (#variable)
Here we simply declared a variable #value inside another variable #variable

How to access a database given a string of its name

Alright so say I have code that looks like this.
CREATE Table database_info
(
DBName NVARCHAR (MAX)
);
INSERT INTO database_info (DBName)
VALUES ('db1')
SELECT * FROM database_info
DECLARE #temp nvarchar(MAX)
SET #temp = (SELECT DBName FROM database_info where database_info.DBName = 'db1')
--How I want it to work SELECT * FROM #temp
Is there any kind of operation I could do on this temporary variable to have the string act as a regular SQL command?
Thanks
You may execute a dynamic sql using EXEC. Now, declaring the #sql variable would be quite too much in this case, but it is useful when you are not sure of the length of the statement you will pass to it.
DECLARE #sql AS VARCHAR(MAX)
SET #sql = 'SELECT * FROM ' + #temp
EXEC(#sql)

How to set a variable to the result of a sql query with a variable as a table name in SQL 2005

I'm currently having trouble writing a stored procedure and setting the value of a variable of type int to the results of a select statement with a variable as the tablename. I've looked at old threads and tried multiple methods, but no luck. If I'm not getting an error regarding the tablename, I end up getting an error with a variable conversion issue. I've been working on this for too long and any help would be appreciated. Below is a portion of my code. Thanks
DECLARE #BATCHNUMBER VARCHAR --value set in earlier code
DECLARE #ETABLE VARCHAR(50); --the table name
DECLARE #FIRSTDOCID INT;
SET #ETABLE = 'tablename_' + #BATCHNUMBER; --CREATE FIRST TABLE NAME
SELECT #FIRSTDOCID = MIN(D0CID) FROM #ETABLE
The error I get is: Must declare the table variable "#ETABLE"
You are trying to select from a VARCHAR, not a table. The only way to make this work is by using Dynamic SQL.
DECLARE #SQL NVARCHAR(250);
SET #SQL = 'SELECT #OUTPUT = MIN(D0CID) FROM ' + QuoteName(#ETABLE);
EXEC sp_executeSql #SQL, N'#output INT OUTPUT', #FIRSTDOCID OUTPUT;
SELECT #FIRSTDOCID;
However, I would not suggest using Dynamic SQL as this often leads to SQL injection.
You'll probably have to do something like use exec if you're dynamically building the query:
SET #QUERY = "SELECT" + ...etc.
exec(#QUERY)
Since ETABLE is a varchar, and not, as expected, a 'table variable'.

Must declare the scalar variable error SQL

I have this SQL statement, but i have error Must declare the scalar variable "#InputPath"
IF OBJECT_ID('DBO.SP_INSERT_REQUESTS') IS NULL BEGIN
EXEC('CREATE PROCEDURE DBO.SP_INSERT_REQUESTS AS RETURN')
GRANT EXECUTE ON DBO.SP_INSERT_REQUESTS TO PUBLIC
END
GO
ALTER PROCEDURE DBO.SP_INSERT_REQUESTS
#Name NVARCHAR(512),
#Code NVARCHAR(50),
#InputPath NVARCHAR(2000),
#OutputPath NVARCHAR(2000)
AS
GO
SET QUOTED_IDENTIFIER OFF
--DECLARE #InputPath varchar(2000) = "c:\MyDoc1.xsd"
DECLARE #InputValue XML
--DECLARE #OutputPath varchar(2000) = "c:\MyDoc2.xsd"
DECLARE #OutputValue XML
DECLARE #QUERY NVARCHAR(4000) SET #QUERY = "
SELECT #InputValue = InputExample.BulkColumn
FROM OPENROWSET (BULK '"+#InputPath+"', SINGLE_BLOB) AS InputExample;
SELECT #OutputValue = InputExample.BulkColumn
FROM OPENROWSET (BULK '"+#OutputPath+"', SINGLE_BLOB) AS InputExample;
"
EXEC SP_EXECUTESQL #QUERY, N'#InputValue XML out, #OutputValue XML out', #InputValue out, #OutputValue out
INSERT INTO MyTable(Name, Code, Input, Output)
VALUES('value1', 'value2' , #InputValue, #OutputValue)
I have declared the parameters, so I don't understand why I am getting the error.
Remove the GO which is between 'AS' and 'SET QUOTED_IDENTIFIER OFF'. The problem is that you declare the variable in a different batch.
Dynamic sql runs in a different session and therefore variables defined outside the dynamic query will not be available to the dynamic query DEMO - HERE.
Then again, if you declare them within the dynamic query, they won't be available outside the query. DEMO - HERE
I can see why you using dynamic sql as you cannot pass parameter to openrowset. I think you could do something like this to over come the issue. DEMO