首先,我认为SET
和SELECT
几乎可以互换。但是当我在以下代码中将SELECT
更改为SET
时,它无法编译。
任何人都可以向我解释为什么会这样?
感谢。
-- Create Procedure
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUT
AS
SELECT @AddressCount = count(*) -- changing 'SELECT' to 'SET' doesn't work
FROM AdventureWorks.Person.Address
WHERE City = @City
-- SQL query to call the procedure
declare @AddressCount int
exec uspGetAddressCount bothell, @AddressCount OUTPUT
select @AddressCount -- Didn't know SELECT can be used to print values ?
答案 0 :(得分:1)
SET和SELECT不可互换。
看起来已经讨论过...... SET vs. SELECT - What's the difference?
再次...... SET versus SELECT when assigning variables?
另外...... http://blog.sqlauthority.com/2007/04/27/sql-server-select-vs-set-performance-comparison/
答案 1 :(得分:0)
Set用于更新变量的值.. 选择是根据给定的条件显示表格
答案 2 :(得分:0)
虽然其他答案很有帮助,但我认为他们没有完全回答这个问题。使用SET和SELECT的方式存在语法差异:
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address WHERE City = @City
变为:
SET @AddressCount = (SELECT count(*)
FROM AdventureWorks.Person.Address WHERE City = @City)
除语法之外的另一个重要区别是,如果查询返回多于1行,则SET将抛出错误,而SELECT将为变量分配返回的最后一行中的值。