What is the difference between SET and SELECT when assigning values to variables, in T-SQL?
2024-10-01 16:38:58
http://vyaskn.tripod.com/differences_between_set_and_select.htm
https://stackoverflow.com/questions/3945361/set-versus-select-when-assigning-variables
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
http://www.sql-server-helper.com/tips/set-vs-select-assigning-variables.aspx
SET | SELECT |
ANSI standard for variable assignment. | Non-ANSI standard when assigning variables. |
Can only assign one variable at a time.
SET @Index = 1 |
Can assign values to more than one variable at a time.
SELECT @Index = 1, @LoopCount = 10, |
When assigning from a query and the query returns no result, SET will assign a NULL value to the variable.
DECLARE @CustomerID NCHAR(5) |
When assigning from a query and the query returns no result, SELECT will not make the assignment and therefore not change the value of the variable.
DECLARE @CustomerID NCHAR(5) |
When assigning from a query that returns more than one value, SET will fail with an error.
SET = (SELECT [CustomerID] |
When assigning from a query that returns more than one value, SELECT will assign the last value returned by the query and hide the fact that the query returned more than one row.
SELECT @CustomerID = [CustomerID] |
最新文章
- 从程序员到CTO的Java技术路线图(我爱分享)
- 介绍两种风格的URL
- [Architecture Design] 累进式Domain Layer
- hdu 2767 Proving Equivalences
- Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)
- easyui 分页实现
- UVA10304---(区间DP)
- 纠错《COM技术内幕》之ProgID
- git 使用系列(二)---- 分支和合并
- Linux指令--wc
- 【BZOJ2004】公交线路(动态规划,状态压缩,矩阵快速幂)
- 深度学习之Batch Normalization
- javascript面向对象习题答案
- AES加解密程序的实现
- Postgresql之VACUUM和VACUUM FULL对比
- ImageView控件有关问题
- JAVA基础知识总结:二十
- 我的TDD实践---CI持续集成
- Windows Sysinternals实战指南
- 【SqlServer】T-SQL的简介及基本用法