我一直认为,对于T-SQL中的单变量赋值,set
是最好的方法,原因有两个:
因此...
SELECT @thingy = 'turnip shaped'
变为
SET @thingy = 'turnip shaped'
但有多快,快?我真的会注意到差异吗?
答案 0 :(得分:9)
单次运行时SET速度更快。你可以很容易地证明这一点。它是否有所作为取决于你,但我更喜欢SET,因为如果所有代码都在进行,我没有看到SELECT的重点。我更喜欢将SELECT限制在表,视图等的SELECT语句中。
这是一个示例脚本,其运行次数设置为1:
SET NOCOUNT ON
DECLARE @runs int
DECLARE @i int, @j int
SET @runs = 1
SET @i = 0
SET @j = 0
DECLARE @dtStartDate datetime, @dtEndDate datetime
WHILE @runs > 0
BEGIN
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SET @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SELECT @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS
SET @runs = @runs - 1
END
结果:
运行#1:
SET_MILLISECONDS
5093
SELECT_MILLISECONDS
5186
运行#2:
SET_MILLISECONDS
4876
SELECT_MILLISECONDS
5466
运行#3:
SET_MILLISECONDS
4936
SELECT_MILLISECONDS
5453
运行#4:
SET_MILLISECONDS
4920
SELECT_MILLISECONDS
5250
运行#5:
SET_MILLISECONDS
4860
SELECT_MILLISECONDS
5093
奇怪的是,如果你将跑步次数设置为10,则SET开始落后。
以下是10个结果:
SET_MILLISECONDS
5140
SELECT_MILLISECONDS
5266
SET_MILLISECONDS
5250
SELECT_MILLISECONDS
5466
SET_MILLISECONDS
5220
SELECT_MILLISECONDS
5280
SET_MILLISECONDS
5376
SELECT_MILLISECONDS
5280
SET_MILLISECONDS
5233
SELECT_MILLISECONDS
5453
SET_MILLISECONDS
5343
SELECT_MILLISECONDS
5423
SET_MILLISECONDS
5360
SELECT_MILLISECONDS
5156
SET_MILLISECONDS
5686
SELECT_MILLISECONDS
5233
SET_MILLISECONDS
5436
SELECT_MILLISECONDS
5500
SET_MILLISECONDS
5610
SELECT_MILLISECONDS
5266
答案 1 :(得分:1)
我不是速度是一个问题,它与分配功能集有关。我刚才遇到this并且SQL Server 2008中有一些新内容......我听说,尝试使用Google搜索SQL Set和Select SQL SERVER 2008
答案 2 :(得分:0)
看看“执行计划”,它应该告诉你你的陈述的每一行的费用