SQL SUBSTRING 与 RIGHT - 最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/503573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL SUBSTRING vs RIGHT - Best Practice
提问by John
I'm trying to find out the best practice when removing characters from the start of a string.
我试图找出从字符串开头删除字符时的最佳实践。
In some languages, you can use MID without a length parameter however, in TSQL the length is required.
在某些语言中,您可以使用不带长度参数的 MID,但是,在 TSQL 中需要长度。
Considering the following code, what is the best practise? (The hex string is variable length)
考虑以下代码,最佳实践是什么?(十六进制字符串是可变长度的)
DECLARE @sHex VARCHAR(66)
SET @sHex = '0x7E260F3DA734AD4BD816B88F485CE501D843DF067C8EDCB8AC7DAD331852E04D'
PRINT RIGHT(@sHex,LEN(@sHex) -2)
PRINT SUBSTRING(@sHex,3,LEN(@sHex) -2)
PRINT SUBSTRING(@sHex,3,65535)
采纳答案by Marc Gravell
Well, the first is more expressive of your intent. The last is clearly messy (hard-coded length etc). I doubt you'd find much performance difference between the first & second, so I'd use the simplest - RIGHT
.
嗯,第一个更能表达你的意图。最后一个显然是混乱的(硬编码长度等)。我怀疑您会发现第一个和第二个之间的性能差异很大,所以我会使用最简单的 - RIGHT
.
Of course, if you are doing this lots, you could write a udf that encapsulates this - then if you change your mind you only have one place to change...
当然,如果你做了这么多,你可以写一个 udf 来封装这个——然后如果你改变主意,你只有一个地方可以改变......
回答by SQLMenace
+1 on the right function, it is much clearer what you want to do
+1在正确的功能上,你想做什么就更清楚了
回答by Andrew Hare
I would use the right
function as it better shows your intent. The substring
function is best used for extracting strings from the middle of a longer string.
我会使用该right
功能,因为它可以更好地显示您的意图。该substring
函数最适用于从较长字符串的中间提取字符串。
回答by Yada
I use the second SUBSTRING because it is more portable. Not all dbms had LEFT and RIGHT.
我使用第二个 SUBSTRING 是因为它更便携。并非所有 dbms 都有 LEFT 和 RIGHT。