3

Currently I have a static pivot sql query defined in a stored procedure in sql server:

ALTER PROCEDURE [dbo].[MonthRepo] 
    -- Add the parameters for the stored procedure here
    @from datetime,
    @to datetime
AS
BEGIN
    DECLARE @cols nvarchar(12)
    DECLARE @query nvarchar(max)

    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT *
    FROM (
        SELECT ROUND(ds.ct_quot_rate,0) AS Quote,
               ROUND(ds.ct_quot_rate,0) AS Quote_Out,
               ds.isin
        FROM ds
        WHERE ds.datum >= @from AND ds.datum <= @to
    ) tbl
    PIVOT (
        COUNT(Quote)
        FOR isin IN(AB000001,
                    AB000002, 
                    AB000003,
                    AB000004,
                    AB000005)
    ) piv
END

How can I define this static code in dynamic query? I have declared 2 variables.

2
  • possible dublicate of: stackoverflow.com/questions/30295640/… Commented Jul 21, 2015 at 9:50
  • @CeOnSql I'm getting this error: Conversion failed when converting date and/or time from character string. Commented Jul 21, 2015 at 13:07

2 Answers 2

4

I think you're after something like this:

    ALTER PROCEDURE [dbo].[MonthRepo] 
        -- Add the parameters for the stored procedure here
        @from datetime,
        @to datetime
    AS
    BEGIN

        DECLARE @cols nvarchar(max)
        DECLARE @query nvarchar(max)

        SET NOCOUNT ON;

        WITH vals AS (
            SELECT DISTINCT isin
            FROM   ds
        )
        SELECT  @cols = COALESCE(@cols + ',','') + '[' + isin + ']'
        FROM    vals

        SET @query = '
            SELECT *
            FROM (
                SELECT ROUND(ds.ct_quot_rate,0) AS Quote,
                       ROUND(ds.ct_quot_rate,0) AS Quote_Out,
                       ds.isin
                FROM ds
                WHERE ds.datum >= @from_param AND ds.datum <= @to_param
            ) tbl
            PIVOT (
                COUNT(Quote)
                FOR isin IN(' + @cols + ' )
            ) piv'

        EXECUTE sp_executesql @query, N'@from_param DATETIME, @to_param DATETIME', @from_param = @from, @to_param = @to
    END
Sign up to request clarification or add additional context in comments.

4 Comments

your definition of @cols is static. I need a definition where the isins automatically added to the stored procedure when I add a new isin in the table ds.
I`ve just added the dynamic pick up of values as they are added to ds table - please have a look above again.
I'm getting an error Unclosed quotation mark after the character string 'DE0)) piv
probably because @cols length was 100 - changed it to max and it generates a valid query - please have a look.
0
CREATE PROCEDURE [dbo].[MonthRepo] 
        -- Add the parameters for the stored procedure here
        @from VARCHAR(20),
        @to VARCHAR(20)
    AS
    BEGIN
    IF OBJECT_ID('tempdb..#T') IS NOT NULL 
DROP TABLE #T

create  table #T
(
  datnum varchar(20),
  quote INT,
  isin VARCHAR(20)
)
insert into #T (datnum,quote,isin)values ('2015-01-01',100,'AB000001'),
('2015-01-01',100,'AB000002'),
('2015-01-02',98,'AB000003'),
('2015-01-02',70,'AB000001'),
('2015-01-03',100,'AB000001')
    DECLARE @statement NVARCHAR(max)
    ,@columns NVARCHAR(max)



SELECT @columns = Isnull(@columns + ', ', '') + N'[' + tbl.isin+ ']'
FROM   (SELECT DISTINCT isin
        FROM   #T) AS tbl
--SELECT @columns
SELECT @statement = '  SELECT *
    FROM (
        SELECT ROUND(ds.quote,0) AS Quote,
               ROUND(ds.quote,0) AS Quote_Out,
               ds.isin
        FROM #T ds
        WHERE ds.datnum >=  CONVERT(datetime,'+''''+@from+''' ,105) AND ds.datnum <=  CONVERT(datetime,'''+@to+''' ,105) 

    ) tbl
    PIVOT (
        COUNT(Quote)
        FOR isin IN(' + @columns+ ')) as PVT

' 

PRINT @statement
EXEC sp_executesql @statement = @statement


    END


EXEC [MonthRepo] @from = '2015-01-01',@to = '2015-01-10'

2 Comments

I get this error msg: Conversion failed when converting date and/or time from character string.
@yuro sorry for the late now only i have seen the comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.