SQL Server: SET @variable và SELECT @variable

Bữa nay tình cờ thấy sự khác biệt gữa SET và SELECT trong SQL Server. Hai đoạn query bên dưới có vẻ như giống nhau nhưng lại trả về kết quả khác nhau.

Lục lọi tìm kiếm trên Google thì thấy được một số gợi ý về sự khác nhau giữa 2 mệnh đề này, nhưng tại sao thì vẫn chưa tìm thấy, chắc tại Microsoft thiết kế như vậy 😀 Ở dưới tui có copy lại một đoạn giải thích khá gọn gàng trên gauravlal.wordpress.com.

 

DECLARE @var VARCHAR(20)

SET @var = ‘JOE’

SET @var = (SELECT NAME FROM master.sys.tables WHERE name =’qwerty’)

SELECT @var

SET @var = ‘JOE’

SELECT @var = NAME FROM master.sys.tables WHERE name = ‘qwerty’

SELECT @var

 

But SQL Server 7.0 introduced the new SET statement for initializing and assigning values to variables and it is also written in to SQL Server 7.0 Books Online as:

“It is recommended that SET @local_variable be used for variable assignment rather than SELECT @local_variable.”
There are some key differences between SET and SELECT, which a SQL developer should know:

1) SET is the ANSI standard way of assigning values to variables, and SELECT is not.

2) SET can only assign one variable at a time, but SELECT can make multiple assignments at once.

MS SQL Server – Differences between the SET and SELECT statements when assigning variables

Chia sẻ:

Thích bài này:

Thích

Đang tải…