I have a problem with find solution on how to put inside procedure 3 different dynamic pivot query (example below) and use it in SSRS where I can't add datasets, there are no fields. Another important thing is that at the beginning of my procedure I have one parameter "#Data_x" as the date when I am trying to ad datasets there is an info: "Define Query Parameters" and on the list is only "#Data_x" which I can't define "manually".
Here is example of dynamic pivot:
DECLARE #PmtCols AS NVARCHAR(MAX), #query_ppl AS NVARCHAR(MAX)
select #PmtCols = STUFF((SELECT ',' + QUOTENAME(number)
from #data
group by number
order by number
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
if OBJECT_ID ('tempdb..##ready') is not null drop table ##ready
set #query = 'SELECT ID,' + #PmtCols + ' into ##ready from
(select number, ID, przerwa_pl from #data) as x
PIVOT
(max(przerwa_pl) for number in (' + #PmtCols + ')) as p'
execute(#query) ;
I tried to function FMTONLY OFF/ON but still nothing. What can I do, please help?
Related
This question already has answers here:
SQL Server : query to loop through
(2 answers)
Dynamic query to Union multiple databases
(1 answer)
Closed last year.
I'm working with a server that creates a database every month with the same tables. The only thing that changes is the database name. I can use this query to create a table of the database names.
Select name
into DB_List
FROM master.sys.databases
where name Like '%DB%' and create_date > '2020-01-01'
Which returns:
DB013120,
DB022920,
DB033120,
etc.
I need to grab the different database names and input them into another query like the one below.
SELECT *
FROM [DB******].[dbo].[Table]
I know that I can use UNION but the problem is that the stored procedure will have to be manually updated every time there is a new database added. Currently running on SQL SERVER 2016
You can just build the UNION dynamically. For SQL Server 2017+:
DECLARE #sql nvarchar(max),
#base nvarchar(max) = N'SELECT *
FROM $db$.dbo.[Table]';
SELECT #sql = STRING_AGG
(REPLACE(#base, N'$db$', QUOTENAME(name)),
' UNION ALL ')
FROM master.sys.databases
WHERE name LIKE N'%DB%'
AND create_date > '20200101';
EXEC sys.sp_executesql #sql;
If you're using an older version (please always state that up front), you could use FOR XML PATH, which is a little messier and requires some whitespace-sensitive cleanup:
DECLARE #sql nvarchar(max),
#base nvarchar(max) = N'SELECT *
FROM $db$.dbo.[Table]';
SELECT #sql = STUFF((SELECT N' UNION ALL
' + REPLACE(#base, N'$db$', QUOTENAME(name))
FROM master.sys.databases
WHERE name LIKE N'%DB%'
AND create_date > '20200101'
FOR XML PATH(''), TYPE).value(N'./text()[1]',N'nvarchar(max)'),1,10, '');
EXEC sys.sp_executesql #sql;
Datatype problem with a SQL Server dynamic pivot query.
UPDATE: code works properly now by using datatype nvarchar(MAX) for both #cols and #query. Thanks for the input those who did.
I'm trying to create a SQL Server dynamic pivot query so I don't need to explicitly name all columns in the query statement (there will be 323 columns in the pivoted table and those might change from time to time).
I've build my pivot attempt off another example here in Stack Overflow, but I'm apparently having trouble with the datatypes. I'm not sure how to resolve the issue, so I'd appreciate some input if you can help with a solution.
For background, the source table MyTable to be pivoted contains the columns and datatypes seen in the screenshot below (left side). A sample of a 'select *' query result of that table is seen in image below (right side).
The SQL query code that I've used to try to create a dynamic pivot is shown here (corrected):
DECLARE #cols AS nvarchar(255),
#query AS nvarchar(255);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.attKey)
FROM MyTable c
FOR XML PATH(''), TYPE).value('.', 'varchar(255)'), 1, 1, '')
set #query = 'SELECT landingId, ' + #cols + ' from
(
select landingId
, attValue
, attKey
from MyTable
) x
pivot
(
max(attValue)
for attKey in (' + #cols + ')
) p '
execute(#query)
I get this error from SSMS when executing:
Msg 8114, Level 16, State 5, Line 5
Error converting data type varchar to real.
Any ideas? Thanks in advance. BT
I am trying to use dynamic sql to pivot one column ("Question") into several columns (Question text) in a table with 7 columns. The corresponding data to the one column I want to pivot is in a single column ("Answer"), but the columns in the pivoted table will be under the new columns (Question text) . I am using bcp to copy the query output to a file, and am getting the error "Unable to resolve column-level collations. Copy out failed." What can I do to address this?
I am using Microsoft Sql Server 17 and bcp through Powershell in SQL Server Agent Jobs. I have already tried using dynamic sql to simply select columns, rather than pivoting the table, and I get the same error.
The above is similar to the table I'm using. I want to Pivot the Question column into 4 separate columns with the answer below the question text. the final table should have one row since the Id is the same.
This is the code that stuffs the Question column into a single column:
DECLARE #cols nVARCHAR(MAX), #DynamicPivotQuery nVARCHAR(max);
set #cols = STUFF((SELECT DISTinct ','+ QUOTENAME(Question) from db.testforpivot FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(MAX)') ,1,1,'')
select #cols;
gives:
This is the code for the dynamic pivot:
SET #DynamicPivotQuery = 'SELECT Id,' + #cols+' ( select Id, name, user, extId, Question, score1 from db.testforpivot ) x pivot ( MAX(Answer)for Question in ('+#cols+')) as pivotResult'
exec sp_executesql #DynamicPivotQuery
when I run the following bcp command, I get the error mentioned above:
bcp "SET QUOTED_IDENTIFIER ON
sql code above here" queryout C:\Users\ssingla\Documents\EvalExportLast24Hrs.txt -c -t -T
I am expecting the following:
etc, with scores next to answers
edit 8/3/19
Thanks to folks who have pointed me in the right direction. The following queries are working for dynamic pivot in MSSMS. The key missing points in existing explanations are that the brackets '[' and ']' resulting from QUOTENAME need to be replaced with empty strings in the dynamic pivot. I will test bcp on Monday:
DECLARE #cols nVARCHAR(MAX),
#DynamicPivotQuery nVARCHAR(max);
select #cols = STUFF((SELECT DISTinct ','+ QUOTENAME(Question) from tempdb.dbo.test FOR XML PATH(''), TYPE).value('.', 'nVARCHAR(MAX)'),1,1,'')
select #cols;
SET #DynamicPivotQuery =
'select *
from
(
select *
from tempdb.dbo.test
) a
pivot
(
max(Answer)
for Question in ('+STUFF(REPLACE(REPLACE(#cols,'[', ''),']',''),1,1,'')+')
) p';
exec sp_executesql #DynamicPivotQuery
I have here a query: (this was modified. thank you SO for the help) and I'm using mssql 2008
SELECT 'Risk','ADAB','Bahrain','Kuwait','Masirah','Qatar' <-- fixed
UNION ALL
select CONVERT(VARCHAR,risk)
,CONVERT(VARCHAR,[ADAB]) as ADAB <-- fixed
,CONVERT(VARCHAR,[Bahrain]) as Bahrain <-- fixed
,CONVERT(VARCHAR,[Kuwait]) as Kuwait <-- fixed
,CONVERT(VARCHAR,[Masirah]) as Masirah <-- fixed
,CONVERT(VARCHAR,[Qatar]) as Qatar <-- fixed
from (select risk, piv_site = risk, site
from qcvqciffull
where (1=1) AND Risk is not null) as ps
pivot (count(piv_site)
for site in ([ADAB], [Bahrain], [Kuwait], [Masirah], [Qatar])) as pvt <-- fixed
I have here a fiddle. Is it possible to turn those fields who have "fixed" text beside it and turn them dynamically? Say, I have a new record coming in, USA for instance. Is there a way for it?
Any help would be much appreciated. Thanks.
For current scenerio, you have to add whatever text will add other than this.
Or
you can go for dynamic pivot which automatically find and create column, where you have to create dynamic query and then execute.
Refer this :- Dynamic Pivot
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Year, ' + #ColumnName + '
FROM #Tablename
PIVOT(SUM(Earning)
FOR Course IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
A while ago I asked for help in creating a pivot table. You guys came through for me and I now have a stored procedure that creates my pivot and can store the results in a new table. The columns are dynamic so will always be different for each transaction in the application.
The issue I have is that my application is MVC and uses Entity Framework. Because the database is modelled I can't create on the fly tables with dynamic column names. In use, EF will never know they are there and neither will my views.
It looks like I need to convert the stored procedure to a LINQ statement that I can then process from the model end.
My stored procedure contains the SQL Server STUFF Function, I do not know how to call this function in a LINQ statement.
EXAMPLE OF SQL WITH SQL STUFF FUNCTION:
DECLARE #cols AS VARCHAR(MAX),
#query AS VARCHAR(MAX);
SELECT #cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + convert(varchar(10), t2.date, 101)
FROM test AS t2
ORDER BY '],[' + convert(varchar(10), t2.date, 101)
FOR XML PATH('')
), 1, 2, '') + ']'
set #query = 'select name, ' + #cols + '
from
(
select name, date, cast(yesno as tinyint) as yesno
from test
) x
pivot
(
max(yesno)
for date in (' + #cols + ')
) p'
execute(#query)
MSDN has this method:
[EdmFunctionAttribute("SqlServer", "STUFF")]
public static string Stuff(
string stringInput,
Nullable<int> start,
Nullable<int> length,
string stringReplacement
)
...but I don't know where I place it and how I use it in LINQ.
Hope that made sense, any help much appreciated!
You can just call the stored procedure via ADO, or using ExecuteStoreQuery<DbDataRecord>