空格不包含在变量中

时间:2017-09-25 05:52:11

标签: sql-server

实际上我正在使用列user_Name来验证User_Name,该列存在于表中。

用户vipul_1出现在表格中,但如果传递数据'vipul_1',它应该返回受影响的0行,而不是返回结果。

 DECLARE @User_Name    NVARCHAR(25)
    SET @User_Name= 'vipul_1       '

3 个答案:

答案 0 :(得分:1)

DECLARE @User_Name as NVARCHAR(25) SET @User_Name= 'vipul_1 ' SELECT LEN(@User_Name)[User_Name] 这明确提及 here

尾随空白不会包含在长度计数中。但它会在字符串的开头包含空格。

例如。

7

这将返回DECLARE @User_Name as NVARCHAR(25) SET @User_Name= ' vipul_1 ' SELECT LEN(@User_Name)[User_Name];

但是,

12

这将返回1,包括开头的空白。

如果你想计算尾随空格,那么只需在末尾添加任何字符并找到长度并减去declare @username as varchar(1000); set @username = 'some_name_here '; -- you are unknown about the content of string. set @username = @username + '_'; select LEN(@username) - 1 as [name_length];

像这样。

<强>查询

$('#et_search_icon').click(function(){
  $('.et-search-form').show();
});

<强> here

答案 1 :(得分:0)

他有尾随空格。它们只是被LEN函数忽略了。请尝试使用DATALENGTH函数。

<form role="search" method="get" id="et-search-form" action="run.php">
<input type="search" class="et-search-field" />
</form>

结果...

DECLARE @User_Name NVARCHAR(25);
SET @User_Name = 'vipul_1       ';
SELECT
    LenVal = LEN(@User_Name),
    DataLenVal = DATALENGTH(@User_Name);

答案 2 :(得分:0)

在Sqlserver中存在RTRIMLTRIM函数,请使用它

select LTRIM( ' vipul_1 ') , RTRIM( ' vipul_1  ') , RTRIM(  LTRIM( ' vipul_1 ') ) 

最新的Sqlserver引入了Trim函数

已更新

SQL Server遵循ANSI / ISO SQL-92规范,请参阅下面的链接。为此,您将字符串与LIKE运算符进行比较,如下所示。

Len 功能也不起作用,请使用 DATALENGTH 代替此(如上所述)。

Why the SQL Server ignore the empty space at the end automatically?

https://dba.stackexchange.com/questions/10510/behavior-of-varchar-with-spaces-at-the-end

Declare @table table (name varchar(50))

insert into @table values ('vipul_1'), ('ajay_1') , ('eeee_1') , ('vipul')

DECLARE @User_Name    NVARCHAR(25)
    SET @User_Name= 'vipul_1       '

if Exists (select * from @table where name  = @User_Name and DATALENGTH(name) = DATALENGTH(@User_Name) )
    Select 0
Else
    Select 1

select * from @table where name  like @User_Name
select * from @table where name  = @User_Name
select  * from @table where name  = @User_Name and DATALENGTH(name) = DATALENGTH(@User_Name) --use DataLength for this 
相关问题