为什么 SQL LEN 函数对包含多个字符的字符串返回“1"? [英] Why does SQL LEN function return '1' for a string with several characters?
问题描述
简单的问题 - 为什么当我在下面的查询中打印 @len
变量的值时,我会得到值 1,而不是 12(指定字符串中的字符数)?
Simple question - why when I print the value of the @len
variable in the query below would I be getting the value 1, instead of 12 (the number of characters in the specified string)?
DECLARE @string varchar
DECLARE @index int
DECLARE @len int
DECLARE @char char(1)
SET @string = 'content loop'
SET @index = 1
SET @len= LEN(@string)
print @len
推荐答案
您对 @string
的声明是错误的.varchar
没有长度.
Your declaration of @string
is wrong. You have no length on the varchar
.
试试这个:
declare @string varchar(255); -- or whatever
您刚刚了解到这种情况下的默认值为 1.
You just learned that the default in this situation is 1.
这在文档中有明确规定.进一步说明,MS SQL 似乎使这变得相当复杂:
This is clearly specified in the documentation. As a further note, MS SQL seems to make this rather complicated:
在数据定义或变量声明中未指定 n 时语句,默认长度为1.当使用时不指定nCAST 和 CONVERT 函数,默认长度为 30.
When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified when using the CAST and CONVERT functions, the default length is 30.
正确的习惯是在使用 varchar
或 nvarchar
时总是包含长度.
The right habit is to always include the length when using varchar
or nvarchar
.
这篇关于为什么 SQL LEN 函数对包含多个字符的字符串返回“1"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!