我有一个要求。
鉴于Test1,Test2,我必须执行类似的操作。
像
这样的东西select * from tblname where column_name like('Test1%','Test2%');
即。这些字符串以逗号分隔
我该如何解决这个问题?
这是在SQL SERVER 2005中。
先谢谢
答案 0 :(得分:3)
您需要创建一个这样的SQL语句:
SELECT
*
FROM
tblname
WHERE
column_name like 'Test1%'
OR
column_name like 'Test2%'
每个案例都需要一个OR
答案 1 :(得分:2)
declare @v varchar(50)
declare @sql varchar(1000)
declare @c int
set @v = ltrim(rtrim(' An Gu an')) -- this is your search creteria
set @sql = 'select * from tblname where '
set @c = charindex(' ', @v)
while @c > 0
begin
set @sql = @sql + 'column_name ' + ' like ''%' +
left(@v,@c-1) +'%'' OR ';
set @v = right(@v, len(@v)-@c)
set @c = charindex(' ', @v)
end
set @sql = @sql + ' column_name like ''%'+@v +'%'''
--sql now contains
--select * from tblname where
-- column_name like '%An%' OR
-- column_name like '%Gu%' OR
-- column_name like '%an%'
exec( @sql)
答案 2 :(得分:1)
Sql server 2005,试试这个
--Lookup Table
DECLARE @Values TABLE(
Column_Name VARCHAR(MAX)
)
INSERT INTO @Values (Column_Name) SELECT 'A'
INSERT INTO @Values (Column_Name) SELECT 'B'
INSERT INTO @Values (Column_Name) SELECT 'ATADA'
INSERT INTO @Values (Column_Name) SELECT 'TADAA'
INSERT INTO @Values (Column_Name) SELECT 'Test123A'
INSERT INTO @Values (Column_Name) SELECT '1Test123A'
--Lookup string and delim
DECLARE @LookupString VARCHAR(MAX)
DECLARE @Delim VARCHAR(1)
SET @LookupString = 'Test1,Test2,TADA'
SET @Delim = ',';
--CREATE A LOOKUP TABLE FOR SPLIT STRINGS
WITH substrings (Val, Remainder) AS(
SELECT CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN @LookupString ELSE LEFT(@LookupString,CHARINDEX(@Delim,@LookupString)-1) END,
CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN '' ELSE RIGHT(@LookupString,LEN(@LookupString) - CHARINDEX(@Delim,@LookupString)) END
UNION ALL
SELECT CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN Remainder ELSE LEFT(Remainder,CHARINDEX(@Delim,Remainder)-1) END,
CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN '' ELSE RIGHT(Remainder,LEN(Remainder) - CHARINDEX(@Delim,Remainder)) END
FROM substrings
WHERE CHARINDEX(@Delim,Remainder) >= 0 AND Val != '' AND Remainder != ''
)
SELECT v.Column_Name,
substrings.Val
FROM @Values v INNER JOIN
substrings ON v.Column_Name LIKE substrings.Val + '%'
答案 3 :(得分:0)
示例代码:
declare @val varchar(100) set @val = '30,31,34,35,24,16'
PRINT REPLACE((','+@val),',','%'' OR MAQL LIKE ''%') + '%'''