日期:2014-05-18  浏览次数:20502 次

如何选择时同时给变量赋值?SELECT @count = [count]
SQL code

    SELECT  @count = [count] 
    FROM [tt] 
    WHERE  [id] = @id



选择时给一个值赋值没问题,
假如一列有多个值,可不可以一次选择同时赋值?
下面代码是错误的,但是是这个意思,
SQL code

SELECT  @count = [count] ,  @count2 = [count2]
    FROM [tt] 
    WHERE  [id] = @id



请高人指导一下。

谢谢。

------解决方案--------------------
不行
可以用表变量
不过
要看你具体做什么
------解决方案--------------------
SQL code

declare @T table (id int,count1 int,count2 int)
insert into @T
select 1,5,4 union all
select 2,8,9


declare @id int set @id=1

declare @count int,@count2 int

select @count=count1,@count2=count2 from @T where id=@id

select @count,@count2
/*
5           4
*/

------解决方案--------------------
探讨
假如有5列值需要赋值到变量中,这样
SELECT @count1 = [count1] FROM [tt] WHERE [id] = @id
SELECT @count2 = [count2] FROM [tt] WHERE [id] = @id
SELECT @count3 = [count3] FROM [tt] WHERE [id] = @id
SELECT @count4 = [c……

------解决方案--------------------
你写的报错是因为那个逗号格式不对
------解决方案--------------------
可以给多个变量赋值的.只要你保证条件最多只返回一行记录就可以了.