将记录从Char列复制到Varchar列后,我无法使用like语句找到该行

Create database testDB
Go

USE [testDB]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TestTable1]
(
    [Col_char] [char](20) NULL,
    [Col_nchar] [nchar](64) NULL,
    [Col_varchar] [varchar](64) NULL,
    [Col_nvarchar] [nvarchar](64) NULL
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

insert into TestTable1 values ('Sumit1%', 'Sumit1%', 'Sumit1%', 'Sumit1%')
insert into TestTable1 values ('Sumit2*', 'Sumit2*', null, 'Sumit2*')

select
    [Col_char], LEN([Col_char]),
    [Col_nchar], LEN([Col_nchar]),
    [Col_varchar], LEN([Col_varchar]),
    [Col_nvarchar], LEN([Col_nvarchar])
from
    TestTable1

这行给我搜索结果
select *
from TestTable1
where 'sumit1' like [Col_varchar]

现在,我将*替换为%并将[Col_char]复制到[Col_varchar]列
update TestTable1
set [Col_varchar] = Replace([Col_char], '*', '%')
where [Col_char] like '%2%'

select * from TestTable1

select * from TestTable1 where 'sumit1' like [Col_varchar]

-- this line is not showing any results
select * from TestTable1 where 'sumit2' like [Col_varchar]

select
    Len(Replace([Col_char], '*', '%')),
    Len(Replace([Col_varchar], '*', '%')), *
from TestTable1

最佳答案

当您有SET ANSI_PADDING ON时,通过在右侧填充空格,CHAR(20)始终为20个字符。

当您将其转换为varchar时,您仍然有20个字符,因此Col_varchar值实际上是"Sumit2% ",因此,您正在寻找以Sumit2开头但末尾有一堆空格的字符串

如果您使用替换值

UPDATE
    TestTable1
SET
    [Col_varchar] = RTRIM(REPLACE([Col_char],'*','%'))
WHERE
    [Col_char] LIKE '%2%'

它应该为您工作。

有关ANSI_PADDING https://msdn.microsoft.com/en-us/library/ms187403.aspx的信息

关于sql - 将记录从Char列复制到Varchar列后,无法在SQL Server 2014中使用like语句找到行,但在2003年就可以了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34270476/

10-11 12:47