Answers:
SELECT @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
SET @ModelID = (SELECT m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast')
有关在TSQL中使用SELECT和SET之间的区别,请参见此问题。
如果此select语句返回多个值(开头不正确):
SELECT
,会为变量分配返回的最后一个值(如womp所说),而不会出现任何错误或警告(这可能会导致逻辑错误)SET
,会发生错误SELECT @ModelID = modelid
FROM Models
WHERE areaid = 'South Coast'
如果您的select语句返回多个值,则会为变量分配最后返回的值。
有关将SELECT与变量一起使用的参考:http : //msdn.microsoft.com/zh-cn/library/aa259186%28SQL.80%29.aspx
declare @ModelID uniqueidentifer
--make sure to use brackets
set @ModelID = (select modelid from models
where areaid = 'South Coast')
select @ModelID
我更喜欢只从声明语句设置它
DECLARE @ModelID uniqueidentifer = (SELECT modelid
FROM models
WHERE areaid = 'South Coast')
您可以使用它,但是请记住您的查询给出1个结果,多个结果将引发异常。
declare @ModelID uniqueidentifer
Set @ModelID = (select Top(1) modelid from models where areaid = 'South Coast')
另一种方式:
Select Top(1)@ModelID = modelid from models where areaid = 'South Coast'
Select @ModelID =m.modelid
From MODELS m
Where m.areaid = 'South Coast'
在这种情况下,如果您返回两个或多个结果,那么您的结果就是最后一条记录。因此,请注意这一点,如果您可能还要返回两条记录,因为您可能看不到预期的结果。
共有三种方法:
以下查询详细说明了每种方法的优缺点:
-- First way,
DECLARE @test int = (SELECT 1)
, @test2 int = (SELECT a from (values (1),(2)) t(a)) -- throws error
-- advantage: declare and set in the same place
-- Disadvantage: can be used only during declaration. cannot be used later
-- Second way
DECLARE @test int
, @test2 int
SET @test = (select 1)
SET @test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error
-- Advantage: ANSI standard.
-- Disadvantage: cannot set more than one variable at a time
-- Third way
DECLARE @test int, @test2 int
SELECT @test = (select 1)
,@test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error
-- Advantage: Can set more than one variable at a time
-- Disadvantage: Not ANSI standard
->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;
->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;
->DECLARE val1 int;
->DECLARE val2 int;
->SELECT student__id,student_name INTO val1,val2 FROM student_details;
--HAPPY CODING--