变量列上的SQL子串

时间:2013-07-29 09:12:07

标签: sql substring

我有一个包含列METADATA的数据库表。此METADATA可能包含也可能不包含字符串。这是示例字符串:

StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5

现在,我想提取StudentNickName:TestName(如果存在)。请注意以下约束:

  • METADATA列并不总是包含值
  • METADATA列可以包含不带StudentNickName子句的值
  • StudentNickName:已修复,TestNName每行不同。

2 个答案:

答案 0 :(得分:0)

对于mssql 2005 +

declare @t table(metadata varchar(200))
insert @t values('StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5')
insert @t values('')
insert @t values('StudentID:1234,StudentName:Thomas,StudentNickName:Tom,StudentLevel:3')


select left(b.a, patindex('%_,%', b.a)) StudentNickName
from @t t cross apply
(select right(metadata, patindex('%_:emaNkciNtnedutS%'
 , reverse('X'+ metadata)))+',' a) b

结果:

StudentNickName
---------------
TestNName

Tom

答案 1 :(得分:0)

在Sql Server中工作

DECLARE @test TABLE(metadata VARCHAR(200))
INSERT @test VALUES('StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5')
INSERT @test VALUES('StudentID:1235,StudentName:TestName1,StudentNickName:TestNName1,StudentLevel:6')
INSERT @test VALUES('StudentID:1236,StudentName:TestName2,StudentNickName:TestNName2,StudentLevel:2')
INSERT @test VALUES('')

SELECT split.s.value('.','VARCHAR(100)') as colname FROM 
(
    SELECT CAST('<s>' + REPLACE(metadata,',','</s><s>') + '</s>' AS XML) col FROM @test
) AS t CROSS APPLY col.nodes('/s') AS split(s)
WHERE split.s.value('.','VARCHAR(100)') LIKE '%StudentNickName%'