Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

sql - 如何通过SQL查询设置变量?(How to set variable from a SQL query?)

I'm trying to set a variable from a SQL query: (我正在尝试通过SQL查询设置变量:)

declare @ModelID uniqueidentifer

Select @ModelID = select modelid from models
where areaid = 'South Coast'

Obviously I'm not doing this right as it doesn't work. (显然,我没有这样做,因为它不起作用。) Can somebody suggest a solution? (有人可以提出解决方案吗?)

Thanks! (谢谢!)

  ask by Mr Cricket translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using SELECT: (使用SELECT:)

SELECT @ModelID = m.modelid 
  FROM MODELS m
 WHERE m.areaid = 'South Coast'

Using SET: (使用SET:)

SET @ModelID = (SELECT m.modelid 
                  FROM MODELS m
                 WHERE m.areaid = 'South Coast')

See this question for the difference between using SELECT and SET in TSQL . (有关在TSQL中使用SELECT和SET之间的区别,请参见此问题 。)

Warning (警告)

If this select statement returns multiple values (bad to begin with): (如果此select语句返回多个值 (开头不正确):)

  • When using SELECT , the variable is assigned the last value that is returned (as womp said), without any error or warning (this may cause logic bugs) (使用SELECT ,将为变量分配返回的最后一个值(如womp所说),而不会出现任何错误或警告(这可能会导致逻辑错误))
  • When using SET , an error will occur (使用SET ,将发生错误)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...