当前位置: 代码迷 >> Sql Server >> 怎么选择时同时给变量赋值?SELECT @count = [count]
  详细解决方案

怎么选择时同时给变量赋值?SELECT @count = [count]

热度:76   发布时间:2016-04-27 14:30:06.0
如何选择时同时给变量赋值?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 @Tselect 1,5,4 union allselect 2,8,9declare @id int set @id=1declare @count int,@count2 intselect @count=count1,@count2=count2 from @T where [email protected]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……

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