如何在sql中根据搜索字符串获取所有记录
我想根据搜索字符串获取所有记录 例如 列名:FileName 在简单的场景中,我可以使用如何在sql中根据搜索字符串获取所有记录,sql,sql-server,Sql,Sql Server,我想根据搜索字符串获取所有记录 例如 列名:FileName 在简单的场景中,我可以使用 Declare @FileName nvarchar(60) = NULL set @FileName = '.jpg' SELECT * FROM JobAttachment WHERE AND Tags LIKE '%' + ISNULL(@FileName ,FileName ) + '%' ORDER BY updated DESC 但在我的情况下,我会 set @FileName
Declare @FileName nvarchar(60) = NULL
set @FileName = '.jpg'
SELECT *
FROM JobAttachment
WHERE AND Tags LIKE '%' + ISNULL(@FileName ,FileName ) + '%'
ORDER BY updated DESC
但在我的情况下,我会
set @FileName = '.jpg,.Png,gif'
那么如何进行这样的查询呢
任何帮助都将不胜感激
谢谢试试这个:
SELECT *
FROM JobAttachment a
JOIN (SELECT t1.nod.value('.', 'varchar(50)') tags
FROM (SELECT Cast('<N>.'
+ Replace(Replace(@FileName, '.', ''), ',', '</N><N>.')
+ '</N>' AS XML) AS format) t
CROSS APPLY format.nodes('/N') AS t1(nod)
WHERE t1.nod.value('.', 'varchar(50)') <> '.') fileformat
ON a.tag LIKE ( '%' + fileformat.tags + '%' )
您可以根据需要创建动态条件
Declare @FileName nvarchar(60) = NULL
set @FileName = '.jpg,.Png,gif'
--append a comma to the string to get correct results with empty strings
--or strings with a single value (no commas)
SET @FileName = @FileName + ',';
declare @x XML
declare @FileSearch nvarchar(max)
select @x = cast( '<F>' + replace ( @FileName,',','</F><F>') + '</F>' as xml)
select @FileSearch = stuff( isnull(@FileSearch , '') +
' OR FileName Like ''%'+ isnull(t.value('.','nvarchar(60)'),'')
+'%''' ,1,3,'')
from @x.nodes('/F') as x(t)
试试这个。拆分输入字符串并使用charindex
所以据我所知,您需要表中存在的所有数据“.jpg”、“.png”、“.gif”?
Declare @FileName nvarchar(60) = NULL
set @FileName = '.jpg,.Png,gif'
--append a comma to the string to get correct results with empty strings
--or strings with a single value (no commas)
SET @FileName = @FileName + ',';
declare @x XML
declare @FileSearch nvarchar(max)
select @x = cast( '<F>' + replace ( @FileName,',','</F><F>') + '</F>' as xml)
select @FileSearch = stuff( isnull(@FileSearch , '') +
' OR FileName Like ''%'+ isnull(t.value('.','nvarchar(60)'),'')
+'%''' ,1,3,'')
from @x.nodes('/F') as x(t)
set @sql = 'select * from test where ' -- entire query goes here
+ @FileSearch
exec sp_executesql @sql
SELECT 'MasterRoomTwo.jpg' a INTO #temp UNION
SELECT 'BedRoom.png' UNION
SELECT 'MasterbedRoom.gif'
DECLARE @FileName NVARCHAR(60)
SET @FileName = '.jpg,.Png,gif'
SELECT *
FROM #temp
JOIN (SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)'))) fs
FROM (SELECT Cast ('<M>' + Replace(@FileName, ',', '</M><M>')
+ '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) ad
on Charindex(fs, a) > 0