我想使用局部变量即。数据类型为INT的@CV_Max_Len作为打印时函数CHAR的参数。以下是我的代码。
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
但我得到以下错误
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near '@CV_Max_Len'.
任何帮助?
答案 0 :(得分:0)
试试这个
convert(char,@CV_Max_Len)
不
convert(char(@CV_Max_Len),@CV_Title)
答案 1 :(得分:0)
回答问题:使用以下内容:
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) + '~'
但是,除非有技术原因要求您使用PRINT语句将结果集输出到“消息”选项卡,否则使用以下两个选项之一 MUCH 会更好没有 CURSOR(两者都可以做柱状格式):