CONVERT(varchar(@MAXLENGTH),x) FROM y

  • Not sure how to google for this ...

    proc outputs to text file.

    for formatting reasons only I want to do this:

    DECLARE @maxlength TINYINT

    SELECT @maxlength = MAX(LEN(x)) FROM y

    -- SELECT @maxlength -- (output is 23)

    SELECT CONVERT(VARCHAR(@maxlength),x) FROM y

    -- this fails.

    SELECT CONVERT(VARCHAR(23),x) FROM y

    -- this works

    Am I being a spanner?

    Thank you.

  • Your final select will have to be dynamic sql.

    You cannot do VARCHAR(@variable).

  • Or this may help.

    declare @maxlength TINYINT = 10

    declare @String Varchar(100) = 'abcdefghijklmnopqrstuvwxyz'

    select @String, LEFT(@String, @maxlength)

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • Oh right, I thought the variable would be evaluated first in it's () and applied to the rest of the statement but I guess I've got this wrong.

    Thanks for the dynamic tip.

    I think I'm having one of those days.

  • Actually Phil's answer is brilliant.

    Great way to think outside the box! :w00t:

  • Perfect, thank you too!

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

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