Question

I want to use a local variable viz. @CV_Max_Len of data type INT as parameter to function CHAR while printing. Following is my code.

declare cd_2 cursor for 
    select compact_disc_id, cd_title, price, category 
    from compact_disc_inventory  for read only

declare @CV_Id int
declare @CV_Title varchar(60), @CV_Category varchar(60)
declare @CV_Price numeric(5,2)

open cd_2

declare @CV_Max_Len int
set @CV_Max_Len = (select max(len(cd_title)) from compact_disc_inventory)
print @CV_Max_Len
fetch next from cd_2 into @CV_Id, @CV_Title, @CV_Price, @CV_Category
-- print 'Id      Title                      Price    Category'

while @@fetch_status = 0
    begin
        print convert(varchar(6),@CV_Id) + space(10) +       convert(char(@CV_Max_Len),@CV_Title) + 
            space(5) + convert(varchar(6),@CV_Price) + space(5) + @CV_Category

        fetch next from cd_2 into @CV_Id, @CV_Title, @CV_Price, @CV_Category
    end



close cd_2
deallocate cd_2

But I get following error

Msg 102, Level 15, State 1, Line 19
Incorrect syntax near '@CV_Max_Len'.

Any help?

Was it helpful?

Solution

To answer the question as asked: use something along the lines of the following:

DECLARE @Test VARCHAR(60),
        @MaxLen INT,
        @Len INT

SET @Test = 'This is a test.'
SET @Len = LEN(@Test)
SET @MaxLen = 30


SELECT @MaxLen,
       '~' + @Test + '~',
       '~' + @Test + REPLICATE(' ', @MaxLen - @Len) + '~'

However, unless there is a technical reason requiring you to use PRINT statements to output a result set to the Messages tab, you would be MUCH better off using one of the two following options without the CURSOR (both of which can do columnar format):

  • SQLCMD command-line utility
  • "Results to File" or "Results to Text" query output options

OTHER TIPS

try this

convert(char,@CV_Max_Len)

not

convert(char(@CV_Max_Len),@CV_Title)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top