作者:LookUp77 | 来源:互联网 | 2023-05-25 19:19
我有一张表(MSG_Inbox)接收短信内容的
id Sender MsgTitle
1 13049653413 281005,1,18,9,3
2 13049653413 281005,1,18
3 13049653413 281005,1
想显示成这样
Sender 店号 进店状况 小品类1 小品类1 小品类2 小品类3 小品类4 小品类5
我的SQL语句是这样的
select id,Sender ,
店号 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))+1),
进店状况 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))),
小品类1 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-1),
小品类1 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-2),
小品类2 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-3),
小品类3 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-4),
小品类4 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-5),
小品类5 = parsename(replace(MsgTitle,',','.'), len(MsgTitle) - len(replace(MsgTitle,',',''))-6)
from MSG_Inbox
现在我的结果为
id Sender 店号 进店状况 小品类1 小品类1 小品类2 小品类3 小品类4 小品类5
1, 13049653413 NULL NULL NULL NULL NULL NULL NULL NULL
2, 13049653413 281005 1 18 NULL NULL NULL NULL NULL
3, 13049653413 281005 1 NULL NULL NULL NULL NULL NULL
第一条错误了 没有取到值 不知道什么原因 大家帮我看看!
12 个解决方案
id Sender MsgTitle
1 13049653413 281005,1,18,9,3
2 13049653413 281005,1,18
3 13049653413 281005,1
SELECT
SUBSTRING(MsgTitle,1,CHARINDEX(',',MsgTitle)-1) AS 店号,
PARSENAME(REPLACE(STUFF(MsgTitle,1,CHARINDEX(',',MsgTitle),''),',',''),4),
PARSENAME(REPLACE(STUFF(MsgTitle,1,CHARINDEX(',',MsgTitle),''),',',''),3),
PARSENAME(REPLACE(STUFF(MsgTitle,1,CHARINDEX(',',MsgTitle),''),',',''),2),
PARSENAME(REPLACE(STUFF(MsgTitle,1,CHARINDEX(',',MsgTitle),''),',',''),1)
FROM TB
IF NOT OBJECT_ID('f_GetStr') IS NULL
DROP FUNCTION [f_GetStr]
GO
--分段截取函数(邹建)
CREATE FUNCTION dbo.f_GetStr(
@s varchar(8000), --包含多个数据项的字符串
@pos int, --要获取的数据项的位置
@split varchar(10) --数据分隔符
)RETURNS varchar(100)
AS
BEGIN
IF @s IS NULL RETURN(NULL)
DECLARE @splitlen int
SELECT @splitlen=LEN(@split+'a')-2
WHILE @pos>1 AND CHARINDEX(@split,@s+@split)>0
SELECT @pos=@pos-1,
@s=STUFF(@s,1,CHARINDEX(@split,@s+@split)+@splitlen,'')
RETURN(ISNULL(LEFT(@s,CHARINDEX(@split,@s+@split)-1),''))
END
GO
--> 生成测试数据表: [tb]
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
GO
CREATE TABLE [tb] ([id] [int],[Sender] [bigint],[MsgTitle] [nvarchar](20))
INSERT INTO [tb]
SELECT '1','13049653413','281005,1,18,9,3' UNION ALL
SELECT '2','13049653413','281005,1,18' UNION ALL
SELECT '3','13049653413','281005,1'
-->SQL查询如下:
SELECT id,Sender ,
店号 = dbo.f_GetStr(MsgTitle,1,','),
小品类1 = dbo.f_GetStr(MsgTitle,2,','),
小品类2 = dbo.f_GetStr(MsgTitle,3,','),
小品类3 = dbo.f_GetStr(MsgTitle,4,','),
小品类4 = dbo.f_GetStr(MsgTitle,5,',')
FROM [tb]
/*
id Sender 店号 小品类1 小品类2 小品类3 小品类4
----------- -------------------- ---------- ---------- ---------- ---------- ----------
1 13049653413 281005 1 18 9 3
2 13049653413 281005 1 18
3 13049653413 281005 1
(3 行受影响)
*/