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

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

Related

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:

dynamic pivot join with table

Having a query with unknown number of rows and a variable as input needs to join to other tables.
I created a StoredPrecodure - FnGetSumScoreHelper(1) returns the table with unknown number of rows. consider 1 as input variable #regionId of sp.
this sp returns the query to be execute and join with other table.
ALTER PROCEDURE [dbo].[SpFnGetSumScoreQuery]
-- Add the parameters for the stored procedure here
#regionId nvarchar(255) ,
#output nvarchar(max) output
AS
BEGIN
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(CategoryId)
from FnGetSumScoreHelper(1)
group by CategoryId
order by CategoryId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #output = 'SELECT PeriodId,' + #cols + ' from
(
select CategoryId, PeriodId, Score
from FnGetSumScoreHelper(1)
) x
pivot
(
sum(Score)
for CategoryId in (' + #cols + ')
) p '
return
and here is how I want to join it to other table:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#SumScoreCategories nvarchar(max)
EXEC SpFnGetSumScoreQuery 1, #SumScoreCategories OUTPUT
select [Period].Id as PeriodId, [period].[Name] as PeriodName,
RegionPeriodScore.AdminScore, RegionPeriodScore.UserScore
from [period] left join RegionPeriodScore on [period].Id = RegionPeriodScore.PeriodId
inner join
(
execute(#SumScoreCategories)
) SumScoreCategories
on RegionPeriodScore.periodid = SumScoreCategories.periodid
I know I can't join with sp but what is the solution for joining with dynamic pivot that needs input variable? as table valued functions cannot execute query.

Reverse Table In SQL

I have query:
SELECT DISTINCT temp.ID,request.RequestTypeID
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
And result of it:
How can I create table like this:
ID|RequestTypeID1|RequestTypeID2
1 | 4| 5
If you have only two values, then the simplest method is aggregation:
SELECT t.ID, MIN(r.RequestTypeID), MAX(r.RequestTypeID)
FROM #MyTempTable6 t JOIN
dbo.FingerMachineUsers fu
ON t.UserNo = fu.ID JOIN
dbo.AppUsers au
ON au.Id = fu.UserId LEFT JOIN
dbo.Requests r
ON r.UserId = fu.UserId
GROUP BY t.ID;
If you have have a variable number of values that you want to present, then the query is much more complicated.
PIVOT operator could be your best friend, if there are always only 2 values each...
Try this query...
Disclaimer: This code is purely based on this answer. (https://stackoverflow.com/a/10404455/6327676)
DECLARE #cols AS NVARCHAR(max),
#query AS NVARCHAR(max);
SET #cols = Stuff((SELECT DISTINCT ',' + Quotename(stff.requesttypeid)
FROM TableName stff
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+ #cols
+ ' FROM (select ID, RequestTypeId FROM TableName) x pivot (MAX(RequestTypeId) FOR RequestTypeId in ('
+ #cols + ')) p'
EXECUTE(#query)
Try this code it will work according to the result you want.
Firstly you need to dump #MyTempTable6 table into #temptable
then set RequestTypeID columns as comma seperated in #colums varible then set the columnname in #Requestcolumns variable,Then use pivot.
DECLARE #colums AS NVARCHAR(max)
DECLARE #Requestcolumns AS NVARCHAR(max)
DECLARE #query AS NVARCHAR(max);
SELECT DISTINCT temp.ID,request.RequestTypeID
into #temptable
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
SET #colums = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID)
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #Requestcolumns = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID) +' AS ',+Quotename('RequestTypeID'+CONVERT(varchar(100),tab.RequestTypeID))
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+#Requestcolumns
+ ' FROM (select ID, RequestTypeID FROM #temptable) x pivot (MAX(RequestTypeID) FOR RequestTypeID in ('
+ #colums + ')) p'
EXECUTE(#query)
DROP table #temptable

dynamic sql query not showing result on server

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.