just have a general question today. I am trying to store the result in a variable however it's not working. I am not trying to do anything fancy rather a simple task. See below:
declare #prizeid bigint;
declare #today datetime;
declare #dayOfMonth int;
declare #year int;
declare #month int;
select #today = getdate();
select #dayOfMonth = Day(#today);
select #year = Year(#today);
select #month = Month(#today);
if #month = 1
begin
select #month = 12
select #year = #year - 1
end
else select #month = #month - 1;
declare #sqlQuery varchar(250);
declare #quantityForSnapShot bigint;
declare #filename varchar(25);
set #prizeid=31
set #filename = 'Prizes_' + REPLACE(STR(#month, 2, 0), ' ', '0') + '_' + ltrim(str(#year));
select #sqlQuery = 'select Quantity from ' + #filename +
' where PrizeID=' + convert(varchar,#prizeid)
EXEC #quantityForSnapShot=#sqlQuery
print #quantityForSnapShot
All I really want is to retreive the Quantity and store it in the var #quantityForSnapShot.
:-)
declare #prizeid bigint;
declare #today datetime;
declare #dayOfMonth int;
declare #year int;
declare #month int;
select #today = getdate();
select #dayOfMonth = Day(#today);
select #year = Year(#today);
select #month = Month(#today);
if (#month = 1)
begin
select #month = 12
select #year = #year - 1
end
else
begin
select #month = #month - 1;
end
declare #sqlQuery nvarchar(MAX); --<-- to be on safe side
declare #quantityForSnapShot bigint;
declare #filename varchar(25);
set #prizeid=31
set #filename = 'Prizes_' + REPLACE(STR(#month, 2, 0), ' ', '0') + '_' + ltrim(str(#year));
select #sqlQuery = N' select #quantityForSnapShot = Quantity ' +
N' from ' + QUOTENAME(#filename) +
N' where PrizeID = #prizeid'
EXECUTE sp_executesql #sqlQuery
,N'#prizeid bigint, #quantityForSnapShot bigint OUTPUT'
,#prizeid , #quantityForSnapShot OUTPUT
SELECT #quantityForSnapShot
You are trying to call this Dynamic sql as it were a stored procedure with a return value. You will need to use an OUTPUT parameter to retrieve the value of #quantityForSnapShot variable from your dynamic sql.
Also I have used QUOTENAME Function to put square brackets [] around the table name, to tell sql server explicitly that it is an object name. A good practice to get in as it can protect you from Sql injection attack.
Also use system stored procedure sp_executesql to execute dynamic sql.
Try This..
Begin Tran
declare #prizeid bigint;
declare #today datetime;
select #today = getdate();
declare #dayOfMonth int;
select #dayOfMonth = Day(#today);
declare #year int;
select #year = Year(#today);
declare #month int;
select #month = Month(#today);
if #month = 1
begin
select #month = 12
select #year = #year - 1
end
else select #month = #month - 1;
declare #sqlQuery varchar(250);
declare #quantityForSnapShot bigint;
declare #filename varchar(25);
set #prizeid=31
set #filename = 'Prizes_' + REPLACE(STR(#month, 2, 0), ' ', '0') + '_' + ltrim(str(#year));
select #sqlQuery = 'select Quantity from ' + #filename +
' where PrizeID=' + convert(varchar,#prizeid)
Set #quantityForSnapShot = #sqlQuery
Create Table #tmp ( Quantity bigint)
INSERT INTO #tmp (Quantity)
EXEC (#sqlQuery)
Set #quantityForSnapShot = (Select Quantity From #tmp)
Select #quantityForSnapShot
print #quantityForSnapShot
Rollback Tran
Related
I am trying to create a unique id based on the given input and the count of the table.
However, I am getting the required output but when using it in program it returns a error stating
SQL Server - An expression of non-boolean type specified in a context
where a condition is expected, near ')'
Here is my code
ALTER PROCEDURE [dbo].[GetpaymentCode]
(
#O_SupplierCode varchar(50) output,
#O_ErrorDesc varchar(100)output
)
AS
BEGIN
declare #Error int
declare #Count char(10)
declare #Qry nvarchar(4000)
declare #QryCondition nvarchar(1000)
DECLARE #Financial_Year VARCHAR(20)
DECLARE #Year VARCHAR(4)
DECLARE #TotalMax VARCHAR(10)
DECLARE #YearMax VARCHAR(10)
DECLARE #TotalCnt INT
DECLARE #YearCnt INT
DECLARE #BillPrefix VARCHAR(5)
DECLARE #BillId VARCHAR(20)
SET #Financial_Year = #O_SupplierCode
SET #BillPrefix = 'P'+SUBSTRING(#Financial_Year,8,2)
PRINT #BillPrefix
TRUNCATE TABLE Tbl_Max
DECLARE #Query NVARCHAR(MAX)
SET #Query = N'WITH T0 AS
(
SELECT MAX(Payment_Id) TotalMax FROM payment_master WHERE Payment_Id
)
, T1 AS
(
SELECT MAX(Payment_Id) YearMax FROM payment_master WHERE Payment_id LIKE ''' + #BillPrefix + '%''
)
INSERT INTO Tbl_Max
SELECT * FROM T0 INNER JOIN T1 ON 1 = 1'
PRINT #Query
EXEC sp_executesql #Query
SELECT #TotalMax = ISNULL(TotalMax,'0'), #YearMax = ISNULL(YearMax,'0') FROM Tbl_Max
IF(#TotalMax != '0')
BEGIN
SET #TotalCnt = CONVERT(INT, SUBSTRING(#TotalMax,6,3)) + 1
END
ELSE
BEGIN
SET #TotalCnt = 1
END
IF(#YearMax != '0')
BEGIN
SET #YearCnt = CONVERT(INT, SUBSTRING(#YearMax,4,2)) + 1
END
ELSE
BEGIN
SET #YearCnt = 1
END
--PRINT #TotalCnt
--PRINT #YearCnt
SET #BillId = #BillPrefix + replace(str(#YearCnt,2),' ','0') + replace(str(#TotalCnt,3),' ','0')
SELECT #BIllId AS BILL_CODE
end
In CTE command in T0 section you have written incomplete where condition.
SELECT MAX(Payment_Id) TotalMax FROM payment_master WHERE Payment_Id =?
I am trying to execute some logic on a remote server using dynamic SQL, but when I set the dynamic SQL and try to call it nothing happens.. If I call the execution without making the execution dynamic it works without issue.
Not sure if what I am trying to do is allowed when passing OUTPUT values but figured I would see if anyone has any thoughts
DECLARE #sqlserver NVARCHAR(MAX) = ''
DECLARE #DBName NVARCHAR(MAX) = ''
DECLARE #parms NVARCHAR(MAX) = N'#output INT OUT', #output INT, #sql NVARCHAR(MAX) = '
;WITH DuplicateStatusCodes AS (
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''Master'' OR Name = ''Unique'' OR Name = ''Duplicate''
)
SELECT ROW_NUMBER() OVER (ORDER BY CodeTypeID) RN, CodeTypeID INTO #temp
FROM DuplicateStatusCodes
GROUP BY CodeTypeID
HAVING COUNT(CodeTypeID) = 3
DECLARE #count INT = (SELECT COUNT(1) FROM #temp)
DECLARE #ctr INT = 1;
IF #count > 0
BEGIN
WHILE #ctr <= #count BEGIN
DECLARE #parms NVARCHAR(MAX) = N''#inneroutput INT OUT'';
DECLARE #inneroutput INT
DECLARE #codeartifact INT = (SELECT CodeTypeID FROM #temp WHERE RN <= 1 * #ctr and RN > 1 * (#ctr - 1))
DECLARE #duplicatestatuscheck NVARCHAR(MAX) = ''SELECT #inneroutput = COUNT(1) FROM eddsdbo.codeartifact_''+CAST(#codeartifact AS VARCHAR)+''''
EXEC sys.sp_executesql #duplicatestatuscheck, #parms, #inneroutput OUT
SELECT #output = #inneroutput
IF #inneroutput > 0
BREAK;
SET #ctr = #ctr + 1;
END
END
ELSE
BEGIN
SELECT #output = ''0''
END
'
DECLARE #linksql NVARCHAR(MAX) = '
DECLARE #sql NVARCHAR(MAX)
DECLARE #parms NVARCHAR(MAX) = N''#output INT OUT''
EXEC '+QUOTENAME(#sqlserver)+'.'+QUOTENAME(#DBName)+'.sys.sp_executesql #sql, #parms, #output = #output OUT'
--This does not work
EXEC sp_executesql #linksql, #parms, #output = #output
PRINT #output
--This works fine
EXEC [RemoteServerName].[DatabaseName].sys.sp_executesql #sql, #parms, #output = #output OUT ```
Appreciate any help
you would need to use OPENROWSET. Something like this:
DECLARE #ServerName VARCHAR(255) = '...'
,#DatabaseName VARCHAR(255) = '...'
,#Pwd VARCHAR(255) = '...'
,#UID VARCHAR(255) = '...'
,#Name VARCHAR(255) = 'Master'
DECLARE #connect varchar(max) = '''Server=' + #ServerName + ';database=' + #DatabaseName + ';Uid=' + #UID + ';Pwd=' + #Pwd + ';'''
declare #sqlstring varchar(max) = 'SET ANSI_NULLS OFF; SET ANSI_WARNINGS OFF;
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''''' + #Name + ''''' '
declare #TheExecutableStr varchar(max) = '
SELECT *
FROM OPENROWSET(''SQLNCLI'', ' + #connect + ',
''' + #sqlstring + ''')'
SELECT #TheExecutableStr
--EXEC(#TheExecutableStr)
Please note you have to count single quote very diligently, hence SELECT #TheExecutableStr. It is for debugging purposes. You can view the query to be executed and actually copy/paste and execute before uncommenting last statement.
Hope it helps.
just noticed, you have sys.sp_executesql within sys.sp_executesql which might be problematic. you might need to find a way to refactor the code.
I'm trying to get a few values from a dynamic SELECT
This is my code:
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 #myTime=mytime, #myNum=' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
EXEC(#sqlCommand)
When I print the SQL command, this is what I get:
SELECT top 1 #myTime=mytime, #myNum=col1
FROM table
WHERE mytime>='Jul 25 2017 4:40PM'
ORDER BY mytime
When I try to EXEC it, I get this error:
Must declare the scalar variable "#myTime".
If I do this:
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
It works well, but I need to use that data.
Thanks in advance.
Use sp_executesql:
exec sp_executesql #sqlCommand,
N'#myNum int output, #myTime datetime2 output, #vardate datetime2',
#myNum = #myNum output,
#myTime = #myTime output,
#vardate = #vardate;
This is a much better way to run SQL code, because handling parameters is built-in.
Simple...use the Variable passing features, make to identify the Output variables last in the list of variables
Rough signature but should get you started #o_sdate, #o_edate, and #o_resp are variables declared outside of the dynamic sql
exec sp_executesql #sql
, N'#sdate date, #edate date, #resp smallint OUTPUT'
, #sdate = #o_sdate, #edate = #o_edate, #resp = #o_resp OUTPUT
You should use "insert exec" to get your variable out off the dynamic sql. Or use a "double-hash"-table.
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
create table #t1 (mytime datetime, col1 varchar(20))
insert #t1 (mytime, col1) EXEC(#sqlCommand)
select #mytime=mytime, #col1=col1 from #t1
I hope you got the idea.
declare #sql as nvarchar(500)=''
set #sql='
declare #N4 as int = 1
declare #ms as nvarchar(100) = concat(''ms'', convert(nvarchar(10), #N4))
select #ms
'
exec #sql
I want output as ms1.
DECLARE #SQL AS NVARCHAR(500)=''
SET #sql='
while (#i <10)
begin
PRINT (''MS_''+#I)
set #i=#i+1
end
'
EXEC(#SQL)
not generating value for #i
i want to put this code in while loop as I want to access ms1 to ms10
Use sp_executesql which supports ouput params
DECLARE #MS VARCHAR(50)
exec sp_executesql N'declare #N4 as int = 1;
SELECT #MS= concat(''ms'', convert(nvarchar(10), #N4))',
N'#MS VARCHAR(50) output', #MS output;
SELECT #MS
Yes, you can use and for that you need to use sp_executesql like this -
Declare #sql as nvarchar(500)='', #Params NVARCHAR(500),
#N4 Int = 1, #ms nvarchar(100)
SET #Params = '#N4 Int, #ms nvarchar(100) OUTPUT'
set #sql= N'SELECT #ms = concat(''ms'', convert(nvarchar(10), #N4))'
EXEC SP_EXECUTESQL #sql, #Params, #N4 = #N4, #ms = #ms OUTPUT
SELECT #ms
Use While statement and string concatenation to get your result :
DECLARE #StartValue INT = 1
DECLARE #EndValue INT = 10
DECLARE #Query VARCHAR(500) = ''
WHILE #StartValue < #EndValue
BEGIN
SET #Query = #Query + 'sms_' + CAST(#StartValue AS VARCHAR) + ','
SET #StartValue = #StartValue + 1
END
SELECT Query
i am getting an error when trying to concatenate date and string.
declare #select varchar(max)
declare #where varchar(max)
set #select = 'select * from tbl Emp........'
#where = ' where Emp.date >='+ cast((cast(getdate() as date)) as varchar(20))
exec(#select+#where)
I also tried to do like below but didn't work:
declare #today varchar(20)
#today = cast((cast(getdate() as date))
#where = 'where Emp.date> =' + '#today'
Try something like this...
declare #select varchar(max)
declare #where varchar(max)
set #select = 'select * from tbl Emp '
set #where = ' where Emp.date >= ''' + CONVERT(varchar(8),getdate(),112) + ''''
exec(#select+#where)
Or an even better option would be something like this.....
DECLARE #Sql nvarchar(max);
DECLARE #Date DATE = GETDATE();
SET #Sql = N' select * from tbl Emp '
+ N' where Emp.date >= #Date'
Exec sp_executesql #Sql
,N'#Date DATE'
,#Date
But why do you even need dynamic sql for this simple query why cant you simply do
DECLARE #Date DATE = GETDATE();
select * from tbl Emp
where Emp.date >= #Date