Want to get selected value - sql-server-2008

declare #qry as varchar(max)
declare #db as varchar(25)
declare #item as varchar(25)
declare #U_Parentcode as varchar(25)
set #U_Parentcode ='CDM51306520'
set #db ='Marda_Test'
set #qry ='select #item =itemcode from ' + #db + '.[dbo].[OITM] where ItemCode=''' + #U_Parentcode +''''
execute (#qry)
print #item
am getting error like 'Must declare the scalar variable "#item".'

The dynamic sql executes in a different context from the context of your code, so basically there isn't an #item variable declared over there.
You need to use sp_executeSql which contains a mechanism to map your variables to variables within the block. The syntax is a but obtuse, but it's obvious when you get used to it.
declare #qry as nvarchar(max)
declare #db as varchar(25)
declare #outsideItem as varchar(25)
declare #U_Parentcode as varchar(25)
set #U_Parentcode ='CDM51306520'
set #db ='Marda_Test'
set #qry ='select #insideItem =itemcode from ' + #db + '.[dbo].[OITM] where ItemCode=''' + #U_Parentcode +''''
execute sp_executesql #qry, N'#insideItem varchar(25) output', #insideItem = #outsideItem output
print #item
The first parameter is the query, same as with exec().
The second parameter is a declaration of all parameters used in the query, in your case #insideItem.
The third (and any subsequent) parameter is a mapping that says which inside parameter should be mapped to which outside parameter.
The output clause (used both on the variable declaration and on the mapping) is a designator that that parameter is used as an output value of the query.

Your declare statements are not included in #qry content.
In addition, why are you even bothering with execute ?
Why not just use a normal query. Parameterize your connection string so that you connect to the correct database and just run a normal query.

Related

Store json query output in variable / use variable in ole automation api post?

I have a ole automation query that sends json data to an rest api. This works great when you hardcode the json data in the query.
I am trying to use the output from a for json query instead.
So my basic goal is to store the json from the query output in a usable variable
I have tried this
but null always gets assigned to the variable
```
declare #JsonOutput xml
EXEC SP_EXECUTESQL #SqlText, N'#JsonOutput xml OUTPUT', #JsonOutput = #JsonOutput OUTPUT
```
the above output does return the json but the #JsonOutput variable never gets set with the JSON data and is unusable..
..................
Update:
I found a work around but was still wondering if there was a better way. I'm loading the json into a temp table then selecting it and stores it in a usable variable and it posts successfully. It does however seem to restrict the amount of json I can put in the temp table field.
'''
set nocount on;
drop table #b
;WITH x(a) as
(
select JSON_QUERY(rtrim(JSON_MODIFY('[]', 'append $', authorIds))) AS authorIds,[bases], [isCircular], [name], 'ts_SOThWL5L' [schemaId], [registryId], [namingStrategy]
FROM [dbo].[vw_bulkDNAPostCreate]
where myid between 600 and 630
FOR JSON PATH, ROOT('dnaSequences')
)
SELECT a INTO #b FROM x
select a from #b
DECLARE #IntVariable INT;
DECLARE #SQLString NVARCHAR(500);
DECLARE #ParmDefinition NVARCHAR(500);
DECLARE #JSON varchar(max);
set #SQLString = N'select #JSONOUT = a from #b'
SET #ParmDefinition = N'#JSONOUT varchar(max) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition,#JSONOUT=#JSON OUTPUT;
--SELECT #JSON;
declare #url nvarchar(222) = N'https://TestApiEndpoint..net'
declare #authHeader nvarchar(222) = N'Basic tokenadskjfldasjfs'
Declare #Body as varchar(max) = #JSON
EXEC [dbo].[MyAPIPostProc]
#authHeader = #authHeader,
#Body = #JSON,
#url = #url
'''

Is it possible to set the select list dynamically in MSSQL server2008?

I have a requirement to populate the select list dynamically, Could you please suggest any solution?
Example:
DECLARE #DATE CHAR
SET #DATE='E.TERMINATION_DATE'
--SET #DATE='E.HIRE_DATE'
SELECT E.ID,E.FIRSTNAME,E.LASTNAME, #DATE FROM DBO.EMPLOYEES E
Is it possible to set the column name in select query?
For some query i need to set the variable #DATE as TERMINATION DATE and for some query i need to set #DATE as E.HIREDATE.
When i will run the query based on the TERMINATION_DATE then i will comment in the other option.
or do you have any other workaround?
You can use the Dynamic sql. But you should read this blog to know about it.
DECLARE #DATE VARCHAR(100),
#SQL VARCHAR(MAX)
IF YOURCONDITION
BEGIN
SET #DATE='E.TERMINATION_DATE'
END
ELSE
BEGIN
SET #DATE='E.HIRE_DATE'
END
SET #SQL = 'SELECT E.ID,E.FIRSTNAME,E.LASTNAME,' + #DATE +' FROM DBO.EMPLOYEES E'
exec sp_executesql #SQL
you can use variables in select query but you should assign that query to some variable and execute that variable
because in SSMS at first it will checks(run time) then it executes. In our scenario the variable is assigning at execution only
so we need to assign it to variable as #coderofcode told
DECLARE #DATE VARCHAR(100),
#SQL VARCHAR(MAX)
SET #DATE='E.TERMINATION_DATE'
SET #SQL = 'SELECT E.ID,E.FIRSTNAME,E.LASTNAME,' + #DATE +' FROM DBO.EMPLOYEES E'
exec(#sql)
I was writing a function for which i need to use execution_date for some case and for some other case i need to use hire_date.
So i think i can now populate this things dynamically and it's a great invention for me. Thanks all specially Giorgi, coder of code and koushik.
I am using this pseudo code here.
--Setting the condition parameters
DECLARE #HIRE_DATE DATETIME,
SET #HIRE_DATE= SELECT MIN(HIRE_DATE) FROM E.EMPLOYEES WHERE E.PERSON_ID>30000
--based on condition setting the variable dynamically.
IF #HIRE_DATE IS NULL
BEGIN
SET #DATE='E.TERMINATION_DATE'
END
ELSE
BEGIN
SET #DATE='E.HIRE_DATE'
END
--setting the sql to execute.
SET #SQL = 'SELECT COUNT(E.NR) AS ACTIVITIES,E.CLI_FIRSTNAME,E.CLI_LASTNAME,E.DEBTORNR,' + #DATE +' FROM DBO.EMPLOYEES E
GROUP BY E.CLI_FIRSTNAME,E.CLI_LASTNAME,E.DEBTORNR,' + #DATE
exec(#sql)

How to use numeric int in exec sp_executesql

Is there any way i can use numeric integer in sp_executesql ?
declare #total_test int
declare #test int
set #sql=N'select #test=count (*) from '+#db+'..'+#table
exec sp_executesql #sql
set #total_test +=#test
The problem is that he will not accept any numeric integet,
i cant even set #sql=N'select count (*)...'
Any ideas? Thanks for your help.
You will need to use the OUTPUT clause with your variable. Also on a side note you must use QUOTENAME() function when concatenating object names to your dynamic sql string, protects you against possible sql injection attack.
declare #total_test int;
declare #test int;
SET #total_test = 0;
set #sql=N'select #test=count (*) from '+ QUOTENAME(#db)+'..'+ QUOTENAME(#table)
EXECUTE sp_executesql #sql
,N'#test int OUTPUT'
,#test OUTPUT
set #total_test +=#test

Sqlserver: Variable database name in create database query is throwing error

Use master
GO
Declare #dbName As VARCHAR(50)
SET #dbName = 'TestDB'
CREATE DATABASE #dbName
Above sqlserver is script is giving me error. Why?
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '#dbName'.
You can not use dynamic sql and ddl as mixed.
Use dynamic sql .
Try this code:
Use master
GO
Declare #dbName As VARCHAR(50)
DECLARE #Q VARCHAR(MAX)
SET #dbName = 'TestDB'
SET #Q='CREATE DATABASE '+ #dbName
EXEC(#Q)
If won't work because you're passing a VARCHAR type and for the creation of a database, it takes an object instead of a Varchar. Else, you'll need to pass the whole query as a string to execution;
Declare #dbName As VARCHAR(50) = 'TestDB'
DECLARE #Creation VARCHAR(50) ='CREATE DATABASE '+ #dbName
EXEC(#Creation)

Stored Procedure Dynamic SQL stored result in variable

I have A stored procedure written
DECLARE #AreaID AS INT
DECLARE #DayPrior AS INT
DECLARE #TableName AS VARCHAR(50)
DECLARE #StoreQuery AS NVARCHAR(MAX)
DECLARE #SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE #ParameterDefinition AS NVARCHAR(2000)
SET #AreaID = 1
SET #DayPrior = 1
SET #TableName = 'Tbl_Lube'
SET #SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
SET #ParameterDefinition = '#AreaID INT,#DayPrior INT,#TableName VARCHAR(50)'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName
PRINT #SQL_ExtractDlSql
I above Stored procedure, I get What I wanted on print, but instead of doing that, I wanted the selected data stores as a variable.
Then what I done is I declared a variable #StoreSql and made some modified into the SQL statement show below:
Variable Declaration:
DECLARE #StoreSql AS NVARCHAR(MAX)
Modified the Code:
SET #SQL_ExtractDlSql = 'SELECT #StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
I executed the code, I get error Must declare the scalar variable "#StoreSql".
I have totally no idea how to deal with this.Any one can help.Beside,I am new to sqlserver,new to stored procedures.
Please don't hesitate to point out my any mistake,any..such as logic or etc. I learn from mistake.
Regards
LiangCk
The dynamic SQL string cannot reference variables from the outer scope. You need to declare it as an output parameter
SET #ParameterDefinition = '#AreaID INT,
#DayPrior INT,
#TableName VARCHAR(50),
#StoreSql NVARCHAR(MAX) OUTPUT'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName,
#StoreSql OUTPUT