Solved

Dynamic T SQL help

Posted on 2013-06-26
4
341 Views
Last Modified: 2013-06-29
Hi I have a requirment to pass the value to Pivot as a column:

The expected query is below:

SELECT
        *
 FROM (
 SELECT distinct [ReadingDateKey], storekey ,   meter
 from [TechnicalBureau].[FactSubMeterReadings]
      
        ) up
PIVOT ( count( meter) FOR  ReadingDateKey IN  ("20130619","20130620","20130621","20130622","20130623","20130624")  ) AS pvt

My Dymic TSQL statement:

DECLARE @ReadingDateKey varchar(200)
DECLARE @sql varchar(1000)
DECLARE @RDT varchar(1000)

drop table #ReadingDateKey

 CREATE TABLE #ReadingDateKey
(
  ReadingDateKey  varchar(8)
)

 
INSERT INTO #ReadingDateKey  (ReadingDateKey)
SELECT  DISTINCT  CAST(ReadingDateKey as varchar)
FROM [TechnicalBureau].[FactSubMeterReadings]
WHERE ReadingDateKey between  
                              Datepart(year,  dateadd( dd,-8, getdate()))*10000
                        +   Datepart(Month, dateadd( dd,-8, getdate()))*100
                        +   Datepart(Day,   dateadd( dd,-8, getdate()))
                        AND Datepart(year,  dateadd( dd,-1, getdate()))*10000
                        +        Datepart(Month, dateadd( dd,-1, getdate()))*100
                        +   Datepart(Day,   dateadd( dd,-1, getdate()))  
-- Creating Column Names for Pivot


SELECT @ReadingDateKey = COALESCE( @RDT +',', '') +
 CAST(ReadingDateKey  as varchar)
from #ReadingDateKey
select   @ReadingDateKey
 SET @sql =  '
SELECT
             *
             FROM (
                  SELECT [ReadingDateKey], storekey ,   meter
                         from [TechnicalBureau].[FactSubMeterReadings]
                        
           ) up
                  PIVOT ( count(meter) FOR  ReadingDateKey IN  ('+ @ReadingDateKey+')  ) AS pvt'

PRINT @sql
EXEC (@sql)

The above dynamic query will  give me an error, becouse it does not pass the double quote to a values  in the IN clause (")

The query result is below:


(6 row(s) affected)

(1 row(s) affected)

SELECT
             *
             FROM (
                  SELECT [ReadingDateKey], storekey ,   meter
                         from [TechnicalBureau].[FactSubMeterReadings]
                        
           ) up
                  PIVOT ( count(meter) FOR  ReadingDateKey IN  (20130619,20130620,20130621,20130622,20130623,20130624)  ) AS pvt
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near '20130619'.

Any help on how to pass the "" to the values?

Thanks in advance
0
Comment
Question by:keplan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 48

Expert Comment

by:PortletPaul
ID: 39280157
in your code:

SELECT @ReadingDateKey = COALESCE( @RDT +',', '') +
 CAST(ReadingDateKey  as varchar)

perhaps try:

SELECT @ReadingDateKey = COALESCE( @RDT +',', '') +
'"' +  CAST(ReadingDateKey  as varchar) + '"'

i.e. add quotes to each ReadingDateKey
0
 

Author Comment

by:keplan
ID: 39280184
Here is the answer:

DECLARE @ReadingDateKey varchar(200)
DECLARE @sql varchar(1000)




 CREATE TABLE #ReadingDateKey
(
  ReadingDateKey  varchar(8)
)

 
INSERT INTO #ReadingDateKey  (ReadingDateKey)
SELECT  DISTINCT  CAST(ReadingDateKey as varchar)
FROM [TechnicalBureau].[FactSubMeterReadings]
WHERE ReadingDateKey between  
                              Datepart(year,  dateadd( dd,-8, getdate()))*10000
                        +   Datepart(Month, dateadd( dd,-8, getdate()))*100
                        +   Datepart(Day,   dateadd( dd,-8, getdate()))
                        AND Datepart(year,  dateadd( dd,-1, getdate()))*10000
                        +        Datepart(Month, dateadd( dd,-1, getdate()))*100
                        +   Datepart(Day,   dateadd( dd,-1, getdate()))  
-- Creating Column Names for Pivot


SELECT @ReadingDateKey = COALESCE( @ReadingDateKey +',', '') +
 + '"' + CAST(ReadingDateKey  as varchar) +'"'
from #ReadingDateKey
 SET @sql =  '
SELECT        *
             FROM (
                    SELECT DISTINCT [ReadingDateKey],d.[Name],   meter
                    from [TechnicalBureau].[FactSubMeterReadings] f
                    JOIN   [Fault].[DimStores]      d
                    ON(f.storekey = d.storekey )
                    AND d.[EffectiveEnd] is null
           ) up
                  PIVOT ( count(meter) FOR  ReadingDateKey IN  ('+ @ReadingDateKey+')  ) AS pvt'

--PRINT @sql
EXEC (@sql)
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 445 total points
ID: 39280188
great! it's finished then?
0
 

Author Closing Comment

by:keplan
ID: 39287636
g
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question