DECLARE #QUERY VARCHAR(200);
SET #QUERY='SELECT COUNT(*) FROM STUD';
I have used this:
EXEC (#QUERY)
EXECUTE sp_executesql #QUERY
but it's not working.
ERROR: Must declare a scalar variable.
how to declare a scalar variable and how to execute this query.
use this
Declare #query nvarchar(max)
Set #query = 'Select count(*) from stud'
EXECUTE sp_executesql #Query
Please try with the following, as you can not execute the string in SSMS directly, You are required to put it in a Temp/Hash table as per your requirement.
DECLARE #QUERY VARCHAR(200);
Declare #tempTabl Table(countval int)
SET #QUERY='SELECT COUNT(*) FROM Blogs';
Insert into #tempTabl
exec (#query)
select * from #tempTabl
Related
I have a dynamic query where in I want to add the value of a local variable to every row of the result set. I have a simplified version of the example below.
While this query works fine:
DECLARE #purchaseDate AS DATE
SET #purchaseDate = '12/23/2020'
SELECT Name, #purchaseDate
FROM Fruits
The similar one in dynamic SQL does not work:
DECLARE #query AS NVARCHAR(MAX),
#purchaseDate AS DATE
SET #purchaseDate = '12/23/2020'
SET #query = 'SELECT Name, #purchaseDate FROM Fruits'
EXEC sp_executesql #query
I get the error
Must declare the scalar variable "#purchaseDate".
So I assumed I might need to declare my purchaseDate inside the query as the dynamic SQL query cannot access the variable. So I tried this:
DECLARE #query AS NVARCHAR(MAX)
SET #query = 'DECLARE #purchaseDate AS DATE' +
'SET #purchaseDate = ' + '12/23/2020 ' +
'SELECT Name, #purchaseDate FROM Fruits'
EXEC sp_executesql #query
But I get the same error message.
How do I go about fixing it?
You can't reference a variable declared outside of a dynamic statement inside a dynamic statement. You need to add the declaration in the parameters and pass the value:
DECLARE #query AS nvarchar(MAX),
#purchaseDate AS date;
SET #purchaseDate = '20201223';
SET #query = 'SELECT Name,#purchaseDate FROM Fruits;';
EXEC sp_executesql #query, N'#purchaseDate date', #purchaseDate = #purchaseDate;
The recommended way to put a variable in dynamic query with a prepared statement:
if OBJECT_ID('Fruits') is not null drop table Fruits
create table Fruits(
name varchar(100)
)
insert into Fruits
values('apple')
DECLARE #purchaseDate AS DATE
SET #purchaseDate = '12/23/2020'
DECLARE #P1 int;
EXEC sp_prepare #P1 output,
N'#purchaseDate date',
N'SELECT Name, #purchaseDate FROM Fruits';
EXEC sp_execute #P1, #purchaseDate;
EXEC sp_unprepare #P1;
Take a look at the Microsoft Doku.
If you are lazy or just want a simple adhoc solution (not recommended):
if OBJECT_ID('Fruits') is not null drop table Fruits
create table Fruits(
name varchar(100)
)
insert into Fruits
values('apple')
DECLARE #query AS NVARCHAR(MAX),
#purchaseDate AS DATE
SET #purchaseDate = '12/23/2020'
set #query = 'SELECT Name, ' + convert(nvarchar(10),#purchaseDate, 12) + ' FROM Fruits'
exec sp_executesql #query
Am unable to insert record when given all the column names in insert
Below is the SP
ALTER PROCEDURE [dbo].[test]
#tab_name nvarchar(50),
#tab_id int,
#tab_n nvarchar(50),
#tab_q int
as
Begin
declare #sql as nvarchar(50);
declare #counts as int;
select #sql='select #cnt=count(*) from '+#tab_name+' where id='+cast(#tab_id as varchar)+';'
exec sp_executesql #sql,N'#cnt int output', #cnt=#counts output
select #counts as counts
if #counts=1
begin
declare #sql1 as nvarchar(50);
select #sql1='update '+#tab_name+' set quantity='+cast(#tab_q as varchar)+' where id='+cast(#tab_id as varchar)+';'
exec sp_executesql #sql1
end
else
begin
declare #sql2 as nvarchar(50);
set #sql2='insert into '+#tab_name+' (id,name,quantity) values ('+CAST(#tab_id as varchar)+','''+#tab_n+''''
set #sql2+=','+CAST(#tab_q as varchar)+');'
select #sql2
exec sp_executesql #sql2
end
End
"
command: exec dbo.test #tab_name='inventory',#tab_id=4,#tab_n='chiku',#tab_q=123
record gets inserted when column names are removed but does not work with column names during insert.
Please help.
Thanks
It is better to use A nvarchar(max) for dynamic queries with parameters.
Because u never know how long the string can be. unless you know the max lenght of the string.
A dba also told me to use N' as prefix before the string to denote Unicode string literals.
Increase #sql variables size like below:
declare #sql as nvarchar(max);
....
declare #sql1 as nvarchar(max);
...
declare #sql2 as nvarchar(max);
I declared a variable #Obj and assign a complete table name 'ODS..Account' to it.
DECLARE #Obj VARCHAR(255)
Then I used it in a query immediately after FROM Clause. I perceive it is just a string, unable to act as a table object. So how can I fix the code to get it works? Cheers
INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,'ODS'
,Id
,SystemModstamp
FROM
#Obj )
You can use a local variable as a scalar value, not as a function. To do this, you need dynamic SQL:
declare #sql varchar(max);
select #sql = '
INSERT Control.dbo.Consistency_Check(Table_Name, Schema_Name, Id, Incremental_DateTime_Column)
SELECT ''#Tab'', 'ODS', Id, SystemModstamp
FROM #Tab
';
select #sql = replace(#sql, '#tab', #tab);
exec sp_executesql #sql;
Slightly different way of doing it with dynamic SQL:
DECLARE #Obj VARCHAR(255) = 'dbo.table'
DECLARE #SQL NVARCHAR(MAX) = ''
SET #SQL = #SQL +
'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,''ODS''
,Id
,SystemModstamp
FROM
' + #Obj + ''
EXEC (#SQL)
You cannot. You probably want to use dynamic query. i.e. workout the SQL query string into a variable and exec using sp_executesql.
You may use the same variable name in the dynamic SQL but I changed it to #p_Tab for the example.
DECLARE #Tab int = 3
DECLARE #SQLString nvarchar(500)
DECLARE #ParmDefinition nvarchar(500) = N'#p_Tab int';
Declare #TableName nvarchar(100) = 'ODS..Account'
/* Build the SQL string dynamicly.*/
SET #SQLString = N'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#p_Tab
,''ODS''
,Id
,SystemModstamp
FROM
'+ #TableName
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#p_Tab = #Tab
Further reference: https://msdn.microsoft.com/en-us/library/ms188001.aspx
I just wanna do a simple query with grouping by "Age_Band".
And to set the parameter to help me change the grouping column easily.
But got an error:
"Each GROUP BY expression must contain at least one column that is not an outer reference. "
How did I make mistake on using the parameter? Thanks a lot
DECLARE #group nvarchar(50);
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,Age_Band
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by #groupcol';
SET #ParmDefinition = N'#groupcol nvarchar(50)';
SET #group=N'Age_Band'
exec sp_executesql #SQLString, #ParmDefinition,
#groupcol = #group;
You cannot use parameter in the group by clause by you can build query string using parameter. Something like this.
DECLARE #group nvarchar(50) = N'Age_Band'; --set col name
DECLARE #SQLString nvarchar(500);
SET #SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,' + #group + '
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by ' + #group;
exec sp_executesql #SQLString;
How do I assign the results of an exec command to a variable. like the below, so when I do select #sql2 I get the result of the executed varchar sql.
declare #sql varchar(500)
declare #sql2 varchar(max)
set #sql = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
--select #sql
set #sql2 = exec(#sql)
select #sql2
Use an output param:
declare #sql nvarchar(500)
declare #xml XML
set #sql = 'set #xml = (SELECT ..... FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE)'
EXEC sp_executesql #sql, N'#xml XML output', #xml = #xml OUTPUT
select #xml
You can use Table Variables. Try like this,
DECLARE #sql TABLE (col1 VARCHAR(500))
DECLARE #sql2 VARCHAR(max)
SET #sql2 = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
INSERT INTO #sql
EXEC (#sql2)
SELECT *
FROM #sql
Please see reference from this link it will show you how to use output parameters
https://support.microsoft.com/en-us/kb/262499