Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

SQL Server LIKE with square brackets works directly but not using variable

I am using square brackets in the like to indicate a range of wildcard characters. The weird thing is that using the expression directly in the statement works correctly, fetching the expected rows. But using the same expression from a variable does not bring any results. Why doesn't it work from the variable?

Works:

SELECT * FROM dbo.Table WHERE Column LIKE '%B[A-Z][A-Z]%';
Results: BAA, BAB, BAC, ... until BZZ

Does'n work:

DECLARE @var VARCHAR(10)
SET @var = N'B[A-Z][A-Z]'
SELECT * FROM dbo.Table WHERE Column LIKE CONCAT('%', @var, '%');

I also tried concatenating with + but still getting zero results (LIKE '%' + @var + '%')

The same expression works when I use only one range in the variable, but I really need to use two ranges

SET @var = N'B[A-Z]'
SELECT * FROM dbo.Table WHERE Column LIKE '%' + @var + '%';
Results: BA, BB, BC, BD, ....
question from:https://stackoverflow.com/questions/66062924/sql-server-like-with-square-brackets-works-directly-but-not-using-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make your variable longer so that it can store the whole pattern. You can see what value the variable actually has with PRINT @var, which will show you the closing square bracket has been dropped.

declare @var varchar(10) = 'B[A-Z][A-Z]'
print @var

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...