Problem in printing contents of a query in a dynamic sql query

  • Hi,

    I am trying to figure out a dynamic sql query content.

    The code is as follows:

    DECLARE @cols NVARCHAR(2000)

    DECLARE @query NVARCHAR(4000)

    SET @query = N'SELECT tID, '+

    @cols +'

    FROM

    (SELECT t2.tID

    , t1.ColName

    , t2.Txt

    FROM Table1 AS t1

    JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p

    PIVOT

    (

    MAX([Txt])

    FOR ColName IN

    ( '+

    @cols +' )

    ) AS pvt

    ORDER BY tID;'

    PRINT @query

    I need to know the contents of @query before executing the @query.

    However the PRINT does not give me anything.

    I would appreciate any help on this. Thanks.

  • SELECT @query

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Try select @query

    print @query depending on how you are running this would only show up in the message line. It is possible it is working but you do not see it.

    Dan

    If only I could snap my figures and have all the correct indexes apear and the buffer clean and.... Start day dream here.

  • Value of @cols variable is NULL. It means that your @query will be NULL also. So, nothing to print!

    Changing "PRINT @query" to "SELECT @query" will confirm the above - you will see the NULL value returned to you!

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

  • Thanks everyone for the help. I appreciate it. Eugene thanks for pointing the @col showing null. I forgot to include the select query containing the @col. Once I put the select query it worked great.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply