我试图从一个SQL查询设置一个变量:
declare @ModelID uniqueidentifer
Select @ModelID = select modelid from models
where areaid = 'South Coast'
很明显,我做得不对,因为它不起作用。谁能提出一个解决方案?
谢谢!
我试图从一个SQL查询设置一个变量:
declare @ModelID uniqueidentifer
Select @ModelID = select modelid from models
where areaid = 'South Coast'
很明显,我做得不对,因为它不起作用。谁能提出一个解决方案?
谢谢!
当前回答
declare @ModelID uniqueidentifer
--make sure to use brackets
set @ModelID = (select modelid from models
where areaid = 'South Coast')
select @ModelID
其他回答
如果查询返回多行,则使用TOP 1。
SELECT TOP 1 @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
您可以使用这个,但请记住,您的查询只给出一个结果,多个结果将抛出异常。
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'
我更喜欢从declare语句中设置它
DECLARE @ModelID uniqueidentifer = (SELECT modelid
FROM models
WHERE areaid = 'South Coast')
declare @ModelID uniqueidentifer
--make sure to use brackets
set @ModelID = (select modelid from models
where areaid = 'South Coast')
select @ModelID
有三种方法:
声明 SET——微软推荐的方法 选择
下面的查询详细说明了每种方法的优点和缺点:
-- 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