我从前端收集了一个字符串,例如
string1 = "java, .net, oracle".
现在我想将此字符串与数据库示例中的字符串进行比较
string2 = "sql, oracle, wcf".
现在我想在SQL Server中以最简单的方式比较这些字符串,以便在将string1与string2进行比较时,因为“oracle”在两者之间是通用的,所以它将返回true。
我知道有一种方法可以根据分隔符String1
拆分,
,然后循环并逐个比较。但这看起来很漫长。 SQL Server中有没有可以执行此操作的功能?
答案 0 :(得分:1)
您可以尝试使用两个与INNER JOIN
结合的派生表:
DECLARE @s1 NVARCHAR(100)='java,.net,oracle';
DECLARE @s2 NVARCHAR(100)='some1,.net,java';
WITH s1Splitted AS
(
SELECT LTRIM(RTRIM(A.B.value('.','nvarchar(max)'))) AS Part
FROM
(SELECT CAST('<x>' + REPLACE(@s1,',','</x><x>') + '</x>' AS XML) AS y) AS x
CROSS APPLY x.y.nodes('/x') AS A(B)
)
,s2Splitted AS
(
SELECT LTRIM(RTRIM(A.B.value('.','nvarchar(max)'))) AS Part
FROM
(SELECT CAST('<x>' + REPLACE(@s2,',','</x><x>') + '</x>' AS XML) AS y) AS x
CROSS APPLY x.y.nodes('/x') AS A(B)
)
SELECT *
FROM s1Splitted AS s1
INNER JOIN s2Splitted AS s2 ON s1.Part=s2.Part
这可以轻松打包到内联表值函数中,您可以轻松调用
SELECT * FROM dbo.MyFunction(@s1,@s2);
如果您期望包含三个邪恶字符的输入,则应将<, > and &
替换为< > and &
,否则XML拆分方法会中断......
当你正在寻找任何平等的存在时,对结果的简单COUNT
就足够了。您可以将您的函数声明为BIT
并在函数级别上进行此评估,或者返回结果集(这将是我的方法)并在外部进行评估...
答案 1 :(得分:0)
@roryap的评论正是您应该对数据库执行的操作。如果您无法执行此操作,则可以创建TVF或SP。这将把字符串作为参数,将其拆分为类似
的表self.window.set_type_hint(Gdk.WINDOW_TYPE_HINT_DOCK)
然后使用xml或任何拆分函数,使表格看起来像这样:
string_to_table
java
.net
oracle
然后加入他们以获得你需要的东西。
答案 2 :(得分:0)
如果您对某些动态SQL
持开放态度我喜欢这个是它以降序返回HITS的数量
Declare @SearchStr varchar(max) ='Cappelletti , Production ,John'
Declare @TableName varchar(150) ='OD'
Declare @FieldName varchar(150) ='[OD-Title]'
Declare @Select varchar(150) ='[OD-Nr],[OD-Title]'
Set @SearchStr = 'Sign(CharIndex('''+Replace(Replace(Replace(@SearchStr,' , ',','),', ',''),',',''','+@FieldName+'))+Sign(CharIndex(''')+''','+@FieldName+'))'
Declare @SQL nvarchar(Max) = 'Select * from (Select '+@Select+',Hits='+@SearchStr+' From '+@TableName + ') A Where Hits>0 Order by Hits Desc'
Exec(@SQL)
返回
OD-Nr OD-Title Hits
2 Cappelletti, John 2
3 Daily Production Summary 1
答案 3 :(得分:0)
Declare @InputString Varchar(50) = 'java, .net, oracle' --<-- String comming in
Declare @Table TABLE (Strings Varchar(50)) --<-- String in the Database
Insert Into @Table Values ('sql, oracle, wcf')
-- Convert to XML Input sting
declare @xml xml = N'<root><r>' + replace(@InputString, ',','</r><r>') + '</r></root>';
WITH DBString AS (
-- Split string stored in the database
SELECT RTRIM(LTRIM(Split.a.value('.', 'VARCHAR(100)'))) Strings
FROM
(SELECT Cast ('<X>' + Replace(Strings, ',', '</X><X>') + '</X>' AS XML) AS Data
FROM @Table
) AS t CROSS APPLY Data.nodes ('/X') AS Split(a) )
,InputStrings AS
(
-- Split String coming in the parameter
select RTRIM(LTRIM(r.value('.','varchar(max)'))) as InputString
from @xml.nodes('//root/r') as records(r)
)
-- Finally Compare the splitted strings word by word
SELECT * , 'True' [Exist]
FROM InputStrings
WHERE EXISTS (SELECT 1
FROM DBString
WHERE InputStrings.InputString = DBString.Strings)