Set parameter inside SQL server execute command - sql

I want to assign the value to a parameter PRGMREFID inside the if-else condition using the execute commands. Each time I try to do that, it shows NULL value assigned to PRGMREFID parameter, and if I place its declare command inside SEt #C, I do not find the parameter PRGMREFID outside of if-else. How to do that pls help.
Below is the patch.
DECLARE #C VARCHAR(MAX)
DECLARE #PRGMREFID VARCHAR(10)
IF 1=1
SET #C = 'set '+ (#PRGMREFID) +' = ''X'' '
else
set #c = ''
EXECUTE(#C)
select #PRGMREFID

To do what you are trying to do you need to use sp_executesql and define the parameter as an output parameter in order to have the value returned to your session's local variable:
DECLARE #C NVARCHAR(MAX)
DECLARE #PRGMREFID VARCHAR(10)
if 1=1
set #C = 'set #PRGMREFID = ''X'' '
else
set #C = ''
exec sp_executesql #C, N'#PRGMREFID VARCHAR(10) output', #PRGMREFID output
select #PRGMREFID

Related

Set declared parameter value and CONCAT column name

I have table with columns Char1, Char2, Char3..... Each of these columns contain some value. I declared variable #i and in while loop I'm trying to concat it to the Char table column name.
Also, I declared parameter #current in my query and then I'm trying to set its value in the query.
set #tmp = cast(#i as varchar(2))
select #current = 'Char' + #tmp
from SerialNumberFormat
where Example = 'XXXXXXXXXX'
When I execute the query #current has value Char1, Char2, Char3...etc, instead the value of the column.
How I can set column value instead column name in #current?
select #current = Concat(Char1, Char2, Char3)
from SerialNumberFormat
where Example = 'X59AA419010045'
Solution which I found and works for me is executing sp_executesql stored procedure
set #SQL = N'select #currentOUT = Char' + #tmp + ' from SerialNumberFormat
where Example = ''XXXXXXXXX'''
SET #ParmDefinition = N'#currentOUT nvarchar(10) OUTPUT'
exec sp_executesql #SQL, #ParmDefinition, #currentOUT = #current OUTPUT
select #current
Dynamic Sql like this may work for you
Declare #i int = 5
Declare #tmp varChar (10) = #i
Declare #Sql nVarChar(Max) = 'select Char' + #tmp + '
from SerialNumberFormat
where Example = ''X59AA419010045'''
exec sp_executesql #Sql

How to set a variable which include another variable in dynamic sql

Here is my Query:-
declare #a nvarchar (150)
declare #b nvarchar (100)
set #b= 'Test'
set #a =('select COUNT(*) from ' +#b + '.dbo.t_ddl_log')
exec (#a)
if (#a='0')
print 'True'
else
print 'False'
It is always printing False even though it should print True.
If I change the variable #b with Test in my count query it works fine.
What is the problem in the query??
The problem is not with the query - the problem is that you mistakenly think that #a should hold the results of the query, while in fact it holds the query itself.
You can use sp_executeSql to get the results you want:
declare #a nvarchar (150),
#b nvarchar (100),
#c int
set #b= 'Test'
set #a =('select #count = COUNT(*) from ' +#b + '.dbo.t_ddl_log')
exec sp_executeSql #a, N'#count int output', #c = #count output
if (#c= 0)
print 'True'
else
print 'False'

SQL Server - Assign value to variable inside Dynamic SQL

I wanted to assign value to out variable inside a dynamic query.
SET #query = 'IF EXISTS(Condition)
BEGIN
--Some action goes here
SET #result= 1
END
ELSE
BEGIN
SET #result= 2
END'
EXEC(#query)
When am trying to execute this query, I am getting an error:
Must declare the scalar variable "#result".
How can I set value to variable inside dynamic query?
Thanks in advance.
Just try this:
DECLARE #result INT
,#query NVARCHAR(MAX);
SET #query = 'IF (1 = 0)
BEGIN
--Some action goes here
SET #result= 1
END
ELSE
BEGIN
SET #result= 2
END';
EXEC sp_executesql #query, N'#result INT OUTPUT',#result = #result OUTPUT
SELECT #result;
You can use sp_executesql in order to execute dynamic T-SQL statement and initialize SQL variables. In the sp_executesql you need to pass the parameter definition and then parameter mappings.
When you Execute a Query String, It is Considered as a separate session, so The variables that you have declared in the current windows won't be accessible whereas you can access the Temporary tables.
So you have to declare the variable inside the string. Your Query can be re-written as below
SET #query = '
DECLARE #result INT
IF EXISTS(Condition)
BEGIN
--Some action goes here
SET #result= 1
END
ELSE
BEGIN
SET #result= 2
END'
EXEC(#query)
Or Store the result in a table variable and access it from there
DECLARE #Tablevar TABLE
(
Result INT
)
SET #query = '
IF EXISTS(Condition)
BEGIN
--Some action goes here
select 1
END
ELSE
BEGIN
SELECT 2
END'
INSERT INTO #Tablevar
EXEC(#query)
select #Result = Result FROM #Tablevar

SQL Function for SumIf 2012 [duplicate]

This question already has an answer here:
Creating SumIf function in SQL Server 2012
(1 answer)
Closed 7 years ago.
I have the following sql function, but not running correctly, the intended returned value is the total
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[SumIf](#ColumnName [varchar](100), #Criteria [varchar](500))
RETURNS [decimal] AS
BEGIN
-- Declare the return variable here
DECLARE #Total Decimal
DECLARE #TableName Decimal
Select #Total = SUM(#ColumnName) from #TableName where #Criteria
RETURN #Total
END
the use syntax would be something like
Select dbo.sumif(fees.fee_amount, Fees.Fee_Code ='B01')
So the tablename would also need to be extracted from the columnname variable passed.
I don't think you will be able to implement your function that way. You're essentially trying to pass an expression to the function which I don't think is possible in SQL Server. You may be able to do it with dynamic SQL passing in strings but not as cleanly as you're hoping.
you need dynamic SQL to do this, but unfortunately you can't use dynamic SQL inside a UDF. try this-
DECLARE #ColumnName [nvarchar](100) = '' --fill in values here
DECLARE #TableName [nvarchar](100) = ''
DECLARE #Criteria [nvarchar](500) = ''
DECLARE #s nvarchar(max)
DECLARE #res bigint
set #s = 'SELECT #result = SUM(' + #ColumnName + ') from ' + #TableName + ' where ' + #Criteria
exec sp_executesql #s, N'#result OUTPUT', #result = #res OUTPUT
select #res
You are way on the wrong track. If you wanted to put sumif() in a select statement, it would need to be a user-defined aggregation function, rather than just a user-defined function. The fact that you've declared #TableName to be decimal and then use it in a from clause points to other issues.
So, my suggestion is that you just do this in-line:
select sum(case when <condition> then <columnname> else 0 end) as sumval
from <tablename>
If you wanted a programming block to put the data together, then use a stored procedure. Something like:
Create FUNCTION [dbo].SumIf(#ColumnName varchar(100),
#TableName varchar(255)
#Criteria varchar(500),
#Total Decimal OUTPUT)
) AS
BEGIN
DECLARE #sql nvarchar(max) = 'Select #Total = SUM(#ColumnName) from #TableName where #Criteria';
set #sql = replace(#sql, '#ColumnName', #ColumnName);
set #sql = replace(#sql, '#TableName', #TableName);
set #sql = replace(#sql, '#Criteria', #Criteria);
sp_execute_sql #sql, N'#total decimal output', #total = #total output;
END;

Can I use variable in condition statement as value with where condition that test that value

I have the following stored procedure:
ALTER proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int
as
DECLARE #value nvarchar(10)
SET #value = 's'+CONVERT(nvarchar(50),#snum)
DECLARE #sqlText nvarchar(1000);
DECLARE #sqlText2 nvarchar(1000);
DECLARE #sqlText3 nvarchar(1000);
declare #g nvarchar(50) = '''g1'''
SET #sqlText = N'SELECT ' + #value + N' FROM dbo.GrideBtable'
SET #sqlText2 = ' where Gnumber = '+#g --here is the problem it error invalid column name -- the #g is value from the table condition
set #sqlText3 = #sqlText+#sqlText2
Exec (#sqlText3) -- here how can i save the result of the exec into varibale
declare #sal nvarchar(50) = #sqlText3
insert employ (name,Snumber,Gnumber,Salary) values(#name,#snum,#gnum,#sal)
QUESTION: How to put in condition variable gets value from the table when i exec it it think that the #g is column but its not its a value from the table to test it so i display one value after the exec the other QUESTION is how to save the result from the exec in variable and then use that value
I'm using SQL Server 2008 (9.0 RTM)
This will be a stored procedure
Thanks in advance
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like ..
ALTER PROC dbo.[insertperoll] #name nvarchar(50) , #snum int , #gnum int
AS
insert employ (name, Snumber, Gnumber, Salary)
select #name
, #sum
, #gnum
, case when #snum = 1 then s1
when #snum = 2 then s2
when #snum = 3 then s3
when #snum = 4 then s4
end as Salary
from dbo.GrideBtable
where Gnumber = #gnum
If your intent is to have the proc retrieve a salary value from a column determined from the parameter snum and then make an insert into employ using the values passed as parameters and the salary retrieved I think you could refactor your procedure to this:
CREATE proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int AS
DECLARE #g NVARCHAR(50) = 'g1'
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT employ (name,Snumber,Gnumber,Salary) '
SET #sql += N'SELECT ' + QUOTENAME(#name, '''')
SET #sql += N', ' + CAST(#snum AS NVARCHAR(50))
SET #sql += N', ' + CAST(#gnum AS NVARCHAR(50))
SET #sql += N', s' + CAST(#snum AS NVARCHAR(50))
SET #sql += N' FROM dbo.GrideBtable'
SET #sql += N' WHERE Gnumber = ' + QUOTENAME(#g, '''')
EXEC (#sql)
Of course you could add the #g variable to the procedure parameters instead of having it hard coded in the procedure and call it as:
EXEC insertperoll #name='john', #snum=10, #gnum=100, #g='g1'
Sample SQL Fiddle (with some assumptions made about table structure)
You could do this using sp_executesql instead of exec() since this will allow you to use parameters, you can use an output parameter to get the value from the query:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT #val = ' + CONVERT(NVARCHAR(10),#snum) +
N' FROM dbo.GrideBtable WHERE Gnumber = #G1';
DECLARE #val INT; -- NOT SURE OF DATATYPE REQUIRED
EXECUTE sp_executesql #SQL, N'#G1 VARCHAR(20), #val INT OUT', 'G1', #val OUT;