如何使用TSQL获取整数的长度 [英] How to get the length of an integer on with TSQL
问题描述
Hello Everyone,
我对在tsql查询中获取整数长度的最佳形式有疑问。
当我这样做时逻辑似乎有效:
Hello Everyone,
I am in doubt about what is the best form to obtain the length of an integer in a tsql query.
The logic seems to work when I do:
//Where @nbr_containers40 is an integer
LEN(@nbr_containers40)
但是从我读过的内容来看,这个函数只能用于字符串,这让我担心可能会出现这样的问题。
所以这是我的问题,我可以保持现状,还是应该更改为:
But from what I've read, this function is meant to work with strings only and this made me worry about possible problems there might come from doing it.
So here is my question, can I keep as it is or should I change to something like:
LEN(CAST(@nbr_containers40 AS varchar(5))
or
LEN(CONVERT(varchar(5), @nbr_containers40))
推荐答案
这里取决于您要提供的数量
请参阅下面的示例
示例1:
Thing here depends on number you are going to give
See the examples below
Example 1:
DECLARE @List Int
SET @List = 11115
SELECT @List as list, CAST(@List AS varchar(5)) as caststring,CONVERT(varchar(5), @List) as convertstring
SELECT len(@List) as directlen,LEN(CAST(@List AS varchar(5))) as cst,LEN(CONVERT(varchar(5), @List)) as conv
Result
list caststring convertstring
11115 11115 11115
directlen cst conv
5 5 5
示例2:
Example 2:
DECLARE @List Int
SET @List = 111115
SELECT @List as list, CAST(@List AS varchar(5)) as caststring,CONVERT(varchar(5), @List) as convertstring
SELECT len(@List) as directlen,LEN(CAST(@List AS varchar(5))) as cst,LEN(CONVERT(varchar(5), @List)) as conv
Result
list caststring convertstring
11115 11115 11115
directlen cst conv
5 5 5
两个例子显示,如果你使用varchar声明convert()或cast()它将仅显示数据lenth声明。如果int有一个字符多于声明数据限制,则它们不会显示它。如果你的变量有一定的限制你可以使用convert()。
Len()函数它自我转换为字符串测量整数变量的长度。 />
即使你想处理它也见下面的例子
Two examples shows, if you are declaring convert() or cast() with varchar it will show upto data lenth declare only. If int has one character more than declare data limit they will not show it. If you your variable has certain limit you can go with convert().
Len() function it self convert as string measures the length of the integer variable.
Even you want to handle it see below example
DECLARE @List Int
SET @List = 1111115
SELECT @List as list, CAST(@List AS varchar) as caststring,CONVERT(varchar, @List) as convertstring
SELECT len(@List) as directlen,LEN(CAST(@List AS varchar)) as cst,LEN(CONVERT(varchar, @List)) as conv
Result
list caststring convertstring
1111115 1111115 1111115
directlen cst conv
7 7 7
这篇关于如何使用TSQL获取整数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!