PRINT not print the dynamic sql - sql

declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT 'A','Z','Geo','SUN'
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(4000)
SET #sQuery='SELECT '+ #sZone + ' = Zone,'+
#sSubCode +' = Sub_Code
FROM'+ #sImport_Table +
' WHERE Geography ='+ #c_Geography +
' AND DayOfWeek = '+ #c_DayOfWeek
PRINT #sQuery
*************** EDITED********************************
declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT 'A','Z','Geo','SUN'
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(4000)
SET #sQuery='''SELECT #sZone = Zone, '+
'#sSubCode = Sub_Code
FROM '+ #sImport_Table +
' WHERE Geography ='''+ #c_Geography + '''
AND [DayOfWeek] = '''+ #c_DayOfWeek +''''''
PRINT #sQuery
sp_executesql #sQuery
PRINT #sZone
PRINT #sSubCode

You have #sZone and #sSubCode which are null. Concatenation with null is always null.
This can make sense.
SET #sQuery='SELECT #sZone = Zone, '+
'#sSubCode = Sub_Code
FROM '+ #sImport_Table +
' WHERE Geography ='+ #c_Geography +
' AND [DayOfWeek] = '+ #c_DayOfWeek
Notice, that the DayOfWeek is reserved word and must be included in square bracket.

Related

How to extract a value from Dynamic SQL result?

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.

Stored procedure not getting called in SQL

I have two stored procedures, one calling the other.Though there is no error at compilation in any of them, but on running SearchProcedure, the outputprocedure is not called from with in. I see no reason it not being called. SearchProcedure has been working fine so far.
Please direct what might be the issue.
I know OutputProcedureis not being called as I tried using Select statements in it.
Here is the code:
Calling as follows:
Exec SearchProcedure #firstname ='Simran', #middlename='kaur', #lastname = 'Khurana', #City='Delhi'
Procedures:
CREATE Procedure OutputProcedure
(
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
)
AS
BEGIN
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int
DECLARE #variableTable TABLE (
idx int identity(1,1),
matchvalue nvarchar(15))
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
declare #sql3 nvarchar(300), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter <= #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #sql = 'declare' +' ' + '#Temp'+ #colVar
exec #sql
select #sql as 'SQLFORDECLARATIONS'
set #temp = CHARINDEX(' ',#sql)
select #temp as 'resultofcharindex'
set #temp2 = #temp + 1
SELECT #temp2 AS 'AFTERADDING1'
set #tempresultStore = Right(#sql, #temp2)
SELECT #tempresultStore AS 'FINALCUTPART'
set #sql3 = 'SET ' + #sql2 + '= set ' + ' ' + #tempresultStore + '=' + 'dbo.[Match' + #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar + 'FromTable' + ',' + 0 + ')'
EXEC #sql3
select #sql3 as 'check sql query formed'
set #finalResult = #finalResult + #sql2
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #Percentage = #finalResult/#maxvalue
SELECT #Percentage AS 'FINALRESULT'
RETURN
END
create procedure SearchProcedure
(
#firstname nvarchar(20),
#middlename nvarchar(20) = null,
#lastname nvarchar(20),
#DOB Date = null,
#SSN nvarchar(30)= null,
#ZIP nvarchar(10)= null,
#StateOfResidence nvarchar(2)= null,
#City nvarchar(20)= null,
#StreetName nvarchar(20)= null,
#StreetType nvarchar(20)= null,
#BuildingNumber int= null,
#Aptnumber nvarchar(10)= null
)
As
DECLARE #sSQL NVARCHAR(2000), #Where NVARCHAR(1000) = ' '
declare #Percent int,
#FN nvarchar(20),
#MN nvarchar(20) = null,
#LN nvarchar(20),
#DateOfB Date = null,
#SSNumber nvarchar(30)= null,
#ZIPCode nvarchar(10)= null,
#StateOfRes nvarchar(2)= null,
#CityOfRes nvarchar(20)= null,
#StreetNameRes nvarchar(20)= null,
#StreetTypeRes nvarchar(20)= null,
#BuildingNumberRes int= null,
#AptnumberRes nvarchar(10)= null
set #Percent = 0
create table #results
(
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
PercentageMatch int not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10)
)
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
open c
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
while ##FETCH_STATUS = 0 BEGIN
/*set #Percent = dbo.[MatchLastName](#lastname, #LN, #Percent)
set #Percent = dbo.[MatchMiddleName](#middlename, #MN, #Percent)
set #Percent = dbo.[MatchCity](#City, #CityOfRes, #Percent)*/
Exec [dbo].[OutputProcedure] #lastname, #LN, #middlename, #MN,#City, #CityOfRes, #Percent output
Insert into #results values
(#FN,#MN,#LN,#Percent, #DateOfB,#SSNumber, #ZIPCode,#StateOfRes,#CityOfRes,#StreetNameRes,#StreetTypeRes,#BuildingNumberRes,#AptnumberRes)
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
end
select * from #results order by PercentageMatch desc
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
go
In SearchProcedure is there code missing that sets variable fn; you open your cursor with
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #FN
only i don't see where #fn is set; if the cursor has no rows then the second procedure won't get called as the loop won't run.

Need for two level reference in T-SQL

By using the dynamic SQL, I created a variable name like this:
set #tempresultStore = 'Temp'+#colVar
Now, #tempresultstore has the value 'TempMiddleName', then I declared this variable named TempMiddleName and assigned the value in the same line in dynamic sql query and executed.
The code is as follows :(Scroll down to code line with comment to follow where the problem is)
CREATE Procedure OutputProcedure
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
AS
BEGIN
SELECT #MiddleNameFromTable AS'middlename'
select #LastNameFromTable as 'LASTNAMEFROMTABLE'
select #LastNameFromUser as 'LASTNAMEFROMUser'
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int , #finalpercentage int = 0
DECLARE #variableTable TABLE
(
idx int identity(1,1),
matchvalue nvarchar(15)
)
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
set #finalResult = 0;
declare #sql3 nvarchar(300), #sql4 nvarchar(15), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
DECLARE #ParmeterDefinition nvarchar(500);
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
#LastNameFromTab nvarchar(20),
#MiddleNameFromUs nvarchar(20),
#MiddleNameFromTab nvarchar(20),
#CityFromUs nvarchar(20),
#CityFromTab nvarchar(20),
#Percent int out'
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter < #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #tempresultStore = 'Temp'+#colVar --here
SELECT #tempresultStore AS 'FINALCUTPART'
select 'JUSTBEFORSQL'
set #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
select #sql3 as 'check sql query formed'
EXEC sp_executesql #sql3,
#ParmeterDefinition,
#LastNameFromUs = #LastNameFromUser,
#LastNameFromTab = #LastNameFromTable,
#MiddleNameFromUs = #MiddleNameFromUser,
#MiddleNameFromTab = #MiddleNameFromTable,
#CityFromUs = #CityFromUser,
#CityFromTab = #CityFromTable,
#Percent = #Percentage out
select #Percentage AS 'PERCENTRETRIVED'
set #finalResult = #finalResult + #Percentage /*here #Percentage always remains 0. It is the value returned by the UDF called by the dynamic SQL above.The function does return the value but probably I fail to store it correctly.*/
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #finalpercentage = #finalResult/#maxvalue
SELECT #finalpercentage AS 'FINALRESULT'
RETURN
END
Go
How do I access the int value stored in variable called #TempMIddleName
It should work with output keyword. No need for creating table. I don't know but your code is not correct. You have output parameter #Percent and assign value of function to #TempMiddleName, then you should have not a #Percent as Output but #TempMiddleName.
You get dynamic SQL
declare #TempMiddleName int = dbo.[MatchMiddleName](MiddleNameFromUser,MiddleNameFromTable, 0)
I had answered you once, that you miss # before your variables.
Also you have provided variable #Percent(and others as well) for dynamic query, but you don't assign any value to it. Try changing
SET #sql3 = 'declare #Temp' + #colVar + ' int = dbo.[Match' + #colVar + '](' + #colVar + 'FromUser,' + #colVar + 'FromTable, 0)'
to
SET #sql3 = 'select #Percent = 1'
and you will see that 1 is returned as supposed to.
Also you have error here. Split first parameter from its type
set #ParmeterDefinition =
N'#LastNameFromUsnvarchar(20),
set #ParmeterDefinition =
N'#LastNameFromUs nvarchar(20),
You would need to dynamically create a temporary table, and access it's value by selecting the top 1 value from it. Something like the following;
CREATE TABLE #ResultValue (Value Varchar(200))
DECLARE #DynamicSql NVarchar(MAX) = ''
SELECT #DynamicSql = '
DECLARE #tempresultStore Varchar(50)
DECLARE #colVar Varchar(50) = ''MiddleName''
SET #tempresultStore = ''Temp'' + #colVar
insert into #ResultValue
select #tempresultStore
'
EXEC sp_sqlexec #DynamicSql
SELECT * FROM #ResultValue
DROP TABLE #ResultValue
If you paste all your code we might try to amend it for you.

Adding two dynamic variable and store it in INT type column

I've two dynamic variable ...
declare #count nvarchar(max)
declare #totalCount int
set #count = ' ( SELECT COUNT(*) FROM '+ #Table +' where [Name] = '''+ CAST(#Name as nvarchar(max)) +''' ) '
set #totalCount = CAST(CAST(#count as nvarchar(max)) + CAST(#Qty as nvarchar(max)) as INT);
I'm getting an error
conversion failed when converting the nvarchar value to datatype int....
then I need to store #totalCount in [TotalCount] column of type INT ...PLease help
he variable table name requires using dynamic SQL. The example below assigns the computed value to the #totalCount variable using a parameterized query output parameter.
DECLARE
#totalCount int
, #Qty int = 5
, #Sql nvarchar(MAX)
, #Table sysname = 'Table'
, #Name nvarchar(MAX) = N'Name';
SET #Sql = N'SELECT #totalCount = COUNT(*) + #Qty
FROM ' + QUOTENAME(#Table) + ' where [Name] = #Name;';
EXEC sp_executesql
#Sql
, N'#Name nvarchar(MAX), #Qty int, #totalCount int OUTPUT'
, #Name = #Name
, #Qty = #Qty
, #totalCount = #totalCount OUT;

sp_executesql not executing dynamic sql

I want to get the value of two variables from dynamic sql .
declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT 'A','Z','Geo','SUN'
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(4000)
SET #sQuery='SELECT #sZone = Zone, '+
'#sSubCode = Sub_Code
FROM '+ #sImport_Table +
' WHERE Geography ='''+ #c_Geography + '''
AND [DayOfWeek] = '''+ #c_DayOfWeek +''''
PRINT #sQuery
sp_executesql #sQuery)
PRINT #sZone
PRINT #sSubCode
You will need to declare this table variable inside the Dynamic sql as dynamic sql has its own scope, variable declared outside of dynamic sql are not visible inside dynamic sql.
And also use OUTPUT clause when trying to retrieve values from a dynamic sql query. Something like this....
declare #sZone nvarchar(50)
declare #sSubCode nvarchar(50)
declare #c_Geography nvarchar(50)='Geo'
declare #c_DayOfWeek nvarchar(50)='SUN'
declare #sImport_Table nvarchar(500)='#sImport_Table1'
--SELECT * FROM #sImport_Table1
declare #sQuery nvarchar(MAX); --<-- to be on safe side
SET #sQuery = N' declare #sImport_Table1 table
(
Id int identity(1,1) ,
Zone nvarchar(50),
Sub_Code nvarchar(50),
Geography nvarchar(50),
DayOfWeek nvarchar(50)
)
INSERT INTO #sImport_Table1 SELECT ''A'',''Z'',''Geo'',''SUN''
SELECT #sZone = Zone, #sSubCode = Sub_Code ' +
N' FROM #sImport_Table1 ' +
N' WHERE Geography = #c_Geography ' +
N' AND [DayOfWeek] = #c_DayOfWeek '
PRINT #sQuery
EXECUTE sp_executesql #sQuery
,N'#c_Geography nvarchar(50),#c_DayOfWeek nvarchar(50),
#sZone nvarchar(50) OUTPUT, #sSubCode nvarchar(50) OUTPUT'
,#c_Geography , #c_DayOfWeek, #sZone OUTPUT, #sSubCode OUTPUT
SELECT #sSubCode, #sZone
Replace
sp_executesql #sQuery)
with
execute sp_executesql #sQuery
Also in dynamic queries you need to declare variables inside your dynamic string.
Otherwise it will throw error.