답변:
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변수에 오류나 경고없이 반환 된 마지막 값이 할당됩니다 (논리 버그가 발생할 수 있음)SET오류가 발생합니다SELECT @ModelID = modelid
FROM Models
WHERE areaid = 'South Coast'
select 문이 여러 값을 반환하면 변수에 마지막으로 반환 된 값이 할당됩니다.
변수와 함께 SELECT를 사용하는 방법에 대한 참조 : http://msdn.microsoft.com/en-us/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
이것을 사용할 수는 있지만 쿼리에서 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'
세 가지 접근 방식이 있습니다.
아래 쿼리는 각각의 장단점을 자세히 설명합니다.
-- 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--