从SQL Server中的#selected字符串中提取单词

时间:2017-09-28 15:59:09

标签: sql sql-server database

我有一个要求,我必须将#分隔的字符串提取为

Declare @Text nvarchar(255) ='Test1#Test2#Test3#Test4'

Declare @FirstWord  nvarchar(255) 
Decalre @SecondWord nvarchar(255)
  • @FirstWord将包含“Test1”和
  • @SecondWord将包含“Test2 Test3 Test4”

2 个答案:

答案 0 :(得分:1)

Declare @Text nvarchar(255) ='Test1#Test2#Test3#Test4'

Declare @FirstWord  nvarchar(255) = left(@Text,(CHARINDEX('#',@Text,1)-1))
Declare @SecondWord nvarchar(255) = replace(right(@Text,len(@Text) - (CHARINDEX('#',@Text,1))),'#', ' ')

select @FirstWord, @SecondWord

答案 1 :(得分:0)

DECLARE @TEXT NVARCHAR(255) = 'Test1#Test2#Test3#Test4'
,@FirstWord NVARCHAR(255)
,@SecondWord NVARCHAR(255)
,@index INT
,@LEN INT

SET @LEN = (
    SELECT LEN(@TEXT)
    )

SELECT @index = (
    SELECT CHARINDEX('#', @TEXT, 1)
    )

SET @FirstWord = (
    SELECT left(@TEXT, @index - 1)
    )
SET @SecondWord = REPLACE(RIGHT(@TEXT, @LEN - @index), '#', ' ')

SELECT @FirstWord AS FirstWord
,@SecondWord AS SecondWord