SQL 服务器 2014

SQL Server 2014

我写了下面的代码。

declare @a int
set @a=select count(*) from Patient
print @a

这段代码有什么问题?

declare @a int 

select @a = count(*) from Patient 
^^^^^^

print @a

如果要使用SET,则必须将SELECT语句括在括号中:

DECLARE @a INT 

SET @a = (SELECT COUNT(*) FROM Patient) 

PRINT @a

如果只想为一个变量赋值,通常使用 set,对多个变量使用 select....

见下面的例子..

declare @a int
set @a=(select count(*) from sales.orders)
print @a


declare @cnt int,@dt datetime

select @cnt=count(*) ,@dt=max(orderdate) from sales.orders