Why does SQL LEN function return '1' for a string with several characters?

空扰寡人 提交于 2019-12-02 04:54:00

问题


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

回答1:


Your declaration of @string is wrong. You have no length on the varchar.

Try this:

declare @string varchar(255);   -- or whatever

You just learned that the default in this situation is 1.

This is clearly specified in the documentation. As a further note, MS SQL seems to make this rather complicated:

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.

The right habit is to always include the length when using varchar or nvarchar.




回答2:


You need to give the variable @string an actual length. Print the variable @string and it will probably return 'C'.




回答3:


Becvause varChar without a length specification is taken as varChar(1)

replace varchar with varChar(30) or varChar(max)



来源:https://stackoverflow.com/questions/16803040/why-does-sql-len-function-return-1-for-a-string-with-several-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!