dynamic sql query not showing result on server - sql

This query shows records when run on my local system, but when I deploy it to and run it on the server, the query does not show any records.
When I connect to the DB server through sql engine and execute (alt + x), it only displays messages command completed successfully, but displays no records.
Any idea how to fix this, where is the issue?
DECLARE #cols AS NVARCHAR(MAX)
, #query AS NVARCHAR(MAX)
select #cols = STUFF
(
(
SELECT ',' + QUOTENAME(StartDateTime)
from
(
select distinct StartDateTime
from tblEmployeeShift
inner join tblShift on tblShift.ShiftId = tblEmployeeShift.ShiftId
where EmployeeNewId = 3126
and IsDeleted = 0
and StartDateTime >= '06/07/2014 12:00:00'
and StartDateTime <= '07/07/2014 12:00:00'
) d
order by StartDateTime
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,''
)
set #query =
N'SELECT EmployeeNewId
,Full_Name
,' + #cols + N'
from
(
select *
from
(
select tblEmployeeShift.EmployeeNewId
,Full_Name
,StartDateTime
,dbo.GetAttendanceFlag(tblEmployeeShift.EmployeeNewId,StartDateTime) as PV
from tblEmployeeShift
inner join tblShift on tblShift.ShiftId = tblEmployeeShift.ShiftId
inner join employee on tblEmployeeShift.EmployeeNewId = SUBSTRING(employee.Employeeid,6,5)
where tblEmployeeShift.EmployeeNewId in
(
select top 20 employeenewid
from employee e
where e.EmployeeNewId = 3126
)
and IsDeleted = 0
) d
)
x pivot
(
max(PV) for StartDateTime in (' + #cols + N')
) c'
execute sp_executesql #query

Most likely the data on the server is such that the #cols variable is NULL, and the concatenation of the NULL #cols variable results in a NULL #query variable.

Related

Insertion failed when converting the nvarchar value to data type int in sql server

I have a XML transposing rows into column query. I am trying to insert the data to a table that is created dynamically. However, I am getting error saying conversion failed when converting nvarchar value to data type int when I execute '#query'
This is my current code:
DECLARE #cols NVARCHAR(MAX), #cols1 NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF(
(
SELECT
','+QUOTENAME(c.[destfieldname] ) + c.datatype
FROM #specnorm c
left join #rawtemp d on c.fieldname = d.fieldname
group by c.destfieldname, c.datatype
order by min(sourceSequenceTypical)
for xml path ('')),1,1,'')+ ', [sequenceID] int, [subsequenceID] int';
SET #cols1 = STUFF(
(
SELECT
','+QUOTENAME(c.[destfieldname] )
FROM #specnorm c
left join #rawtemp d on c.fieldname = d.fieldname
group by c.destfieldname
order by min(sourceSequenceTypical)
for xml path ('')),1,1,'')+ ', [sequenceID],
[subsequenceID] ';
SET #query = ' SELECT '+#cols1+' from (SELECT
c.[rownumber],
c.[contents],
d.[destfieldname]
FROM #rawtemp c
left join #specnorm d on c.fieldname = d.fieldname
)x pivot (max(contents) for destfieldname in ('+#cols1+')) p'
exec ('CREATE Table dbo.sample' + ' (' +#cols + ')');
exec ('Insert into dbo.sample' + #query)
try:
SET #query = 'SELECT '+#cols+' into YOURTABLE from (SELECT
[rownumber],
[contents],
[fieldname]
FROM #rawtemp
) x pivot (max(contents) for fieldname in ('+#cols+')) p'
it creates YOURTABLE on the fly

How To Join Pivot Query Output with CTE Output

I Have one CTE Query
WHICH Return This Output :-
I Have Another SQL Statement(With Pivot Query) Which has Following Output :-
I Want to Join Both Output in Single Query output.
I Have Tried to JOIN This Both Query. but, I can't.
I need to show TotalTraffic and UniqueAttendee(both column) output with Pivot table Output.
I want both output in one table format to show it.
my Code is below for both Output:
---output 1 Query(CTE):
;WITH Detailstbl AS (
SELECT
[S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,COUNT(DISTINCT [VAL].[UserID]) [UniqueAttendee]
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title]
)
SELECT * FROM Detailstbl;
---output 2 Query(Pivot):
DROP TABLE #tempTable
CREATE TABLE #tempTable
(
Title nvarchar(MAX),
TotalTraffic int,
viewdate nvarchar(50)
)
--inserthere
INSERT INTO #tempTable (Title,TotalTraffic,viewdate)
SELECT [S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,CONVERT(VARCHAR(10), [ViewedOn], 101) AS [ViewedDate]
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title],CONVERT(VARCHAR(10), [ViewedOn], 101)
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.viewdate)
FROM #tempTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT #cols
set #query = '
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) AS x '
execute(#query)
PRINT #query
Below what I have tried but getting error Incorrect syntax near ON
set #query = '
SELECT *
FROM Detailstbl
INNER JOIN(
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) AS x ON Detailstbl.Title = x.Title
)'
execute(#query)
PRINT #query
The place where you written the On Clause is incorrect. it should be after the last ')' and you can't use the CTE inside this Dynamic SQL. better try to insert the CTE data into a TempTable Named #Detailstbl
Temp table
SELECT
[S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,COUNT(DISTINCT [VAL].[UserID]) [UniqueAttendee]
INTO #Detailstbl
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title]
Dynamic SQL
set #query = '
SELECT *
FROM #Detailstbl dtbl
INNER JOIN(
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) dt
) x ON dtbl.Title = x.Title '

SQL Server Dynamic Pivoting - Not Usal Pivot With Count

I need to Pivot Questions With Their Answers.The Desired Output of the pivot Query is below and the table structure too.
I have Created the SQL fiddle Here Sql Fiddle. I saw many examples of count with pivot but couldn't find something similar to this.
You simply need some joins to get the base data and a dynamic pivot to show the result in the desired format.
try the following:
drop table if exists #temp
--base table with all details
select s.ID SurveyID, s.SubmittedBy, sq.Question, sa.Answer
into #temp
from #Survey s
join #SurveyMaster sm on sm.ID = s.SurveyMasterID
join #SurveyQuestion sq on sq.SurveyMasterID = s.SurveyMasterID
join #SurveyAnswers sa on sa.SurveyQuestionID = sq.ID and sa.SurveyID = s.ID
--dynamic pivot
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Question)
FROM #temp c
ORDER BY 1 DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT SurveyID, SubmittedBy, ' + #cols + ' from
(
select SurveyID, SubmittedBy, Question, Answer
from #temp
) x
pivot
(
max(Answer)
for Question in (' + #cols + ')
) p '
--execution
execute(#query)
Please find the db<>fiddle here.
declare #sqlstring as varchar(max) = '';
SELECT
#sqlstring = STUFF((
SELECT distinct
',' + '[' + isnull(sq.Question, '''') + ']'
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID FOR XML PATH('')), 1, 1, '')
select
sa.SurveyID,
sv.SubmittedBy,
sq.Question,
sa.Answer into ##temp
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID
set
#sqlstring = 'SELECT SurveyID,SubmittedBy,' + #sqlstring + ' FROM (select * from ##temp ) t ' + ' PIVOT ( ' + ' max(Answer) FOR Question IN (' + #sqlstring + ' ) ) AS pivot_table' execute(#sqlstring);
RESULT:

operation not allowed when the object is closed when running more advanced query

When I try to run a more advanced SQL query on an ASP page I get this error:
operation not allowed when the object is closed
When I run this code it's working:
...
sql = "SELECT distinct team FROM tbl_teams"
rs.open sql, conndbs, 1, 1
...
But when I run this code (and this code is working if I run it in Microsoft SQL Server Management Studio), I get the error...
...
sql = "DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX), #orderby nvarchar(max), #currentYear varchar(4) select #currentYear = cast(year(getdate()) as varchar(4)) select #cols = STUFF((SELECT ',' + QUOTENAME(year([datefrom])) from tbl_teams group by year([datefrom]) order by year([datefrom]) desc FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') select #orderby = 'ORDER BY ['+cast(year(getdate()) as varchar(4)) + '] desc' set #query = 'SELECT team, Won = [1], Lost=[2], Draw = [3]' + #cols + ', Total from ( select team, new_col, total from ( select team, dt = year([datefrom]), result, total = count(*) over(partition by team) from tbl_teams ) d cross apply ( select ''dt'', dt union all select ''result'', case when dt = '+#currentYear+' then result end ) c (old_col_name, new_col) ) x pivot ( count(new_col) for new_col in ([1], [2], [3],' + #cols + ') ) p '+ #orderby exec sp_executesql #query"
rs.open sql, conndbs, 1, 1
...
This is a better overview of the query:
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#orderby nvarchar(max),
#currentYear varchar(4)
select #currentYear = cast(year(getdate()) as varchar(4))
select #cols
= STUFF((SELECT ',' + QUOTENAME(year([datefrom]))
from tbl_teams
group by year([datefrom])
order by year([datefrom]) desc
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #orderby = 'ORDER BY ['+cast(year(getdate()) as varchar(4)) + '] desc'
set #query = 'SELECT team, Won = [1],
Lost=[2], Draw = [3]' + #cols + ', Total
from
(
select
team,
new_col,
total
from
(
select team,
dt = year([datefrom]),
result,
total = count(*) over(partition by team)
from tbl_teams
) d
cross apply
(
select ''dt'', dt union all
select ''result'', case when dt = '+#currentYear+' then result end
) c (old_col_name, new_col)
) x
pivot
(
count(new_col)
for new_col in ([1], [2], [3],' + #cols + ')
) p '+ #orderby
exec sp_executesql #query
Do I need to run the query on another way or what is wrong with this code?
This is a common problem caused by row counts being interpreted as output from a Stored Procedure when using ADODB with SQL Server.
To avoid this remember to set
SET NOCOUNT ON;
in your Stored Procedure this will stop ADODB returning a closed recordset, or if for whatever reason you don't want to do this (not sure why as you can always use ##ROWCOUNT to pass the row count back), you can use
'Return the next recordset, which will be the result of the Stored Procedure, not
'the row count generated when SET NOCOUNT OFF (default).
Set rs = rs.NextRecordset()
which returns the next ADODB.Recordset if ADODB has detected one being returned by the Stored Procedure (might be best to check rs.State <> adStateClosed when dealing with multiple ADODB.Recordset objects).

while converting column to row not able to fetch value from another table automatically

select *
from (
select vtid, convert(date, dtime) as Date from Transaction_tbl where locid = 5
) as vt
pivot (
count(vtid)
for vtid in (select vtid from VType_tbl)
) as pvt
while executing this query am getting error
Incorrect syntax near the keyword 'select'." and Incorrect syntax near
')'.
actually I have one more table,name= Vtype_table , How Can I load all vtid from vtype table in this query? I want to get output depend upon vtid.
Any help greatly appreciated.
Your PIVOT syntax is correct except you are using a SELECT statement inside your PIVOT.
You cannot use a SELECT statement inside the PIVOT IN clause to select column headers. It is required that the columns for the IN clause be known prior to executing the query.
If you are looking to generate a dynamic list of vtid values, then you will need to use dynamic SQL to get the result and the syntax will be similar to the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vtid)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select vtid, convert(date, dtime) as Date
from Transaction_tbl
where locid = 5
) d
pivot
(
count(vtid)
for vtid in (' + #cols + ')
) p '
execute(#query);
Edit, if you want the type names to appear then you should be able to use the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vt_name)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select v.vt_name, convert(date, dtime) as Date
from Transaction_tbl t
inner join VType_tbl v
on t.vtid = v.vtid
where locid = 5
) d
pivot
(
count(vt_name)
for vt_name in (' + #cols + ')
) p '
execute(#query)
Note: I am guessing on the column name for VType_tbl