我有{taskId}={owner}的形式的T-SQL记录,我想把它分成taskId的和所有者的记录(在单独的字段中)。我发现了一个类似的问题的解决方案,启发了这段代码,似乎95%的方式
SELECT [taskId]= LEFT(s.owner, ca.pos - 1),
[owner] = SUBSTRING(s.owner, ca.pos + 1, 888000)
FROM (SELECT [GROUP_TASK_IDS] from [mydb][MyGroupTasks) s
CROSS APPLY (VALUES(CHARINDEX('=', s.owner))) ca(pos)
嵌套的(选择…)s预计返回记录所以我想交叉应用提供了一个连接的机制将函数应用到每个记录的记录集,然后到外面的选择。我对CROSS APPLY有什么误解,我如何纠正我的用法,从{taskId}={owner}的字符串的SELECT'ed记录中返回taskId's和所有者的表?
我假设以下示例数据:
CREATE TABLE MyGroupTasks ([GROUP_TASK_IDS] VARCHAR(100) PRIMARY KEY)
INSERT INTO dbo.MyGroupTasks (GROUP_TASK_IDS)
VALUES ('{123}={456}'),('{a}={bc}')
在这种情况下,我在您的查询中添加了AS owner
以使其有效:
SELECT [taskId]= LEFT(s.owner, ca.pos - 1),
[owner] = SUBSTRING(s.owner, ca.pos + 1, 888000)
FROM (SELECT [GROUP_TASK_IDS] AS owner from MyGroupTasks) s
CROSS APPLY (VALUES(CHARINDEX('=', s.owner))) ca(pos)
,它产生以下结果:
taskId owner
------------------------------ ------------------------------
{123} {456}
{a} {bc}
(2 rows affected)
如果你想要这些结果:
taskId owner
------------------------------ ------------------------------
123 456
a bc
(2 rows affected)
这样修改你的查询:
SELECT [taskId]= SUBSTRING(s.owner, 2, ca.pos - 3),
[owner] = SUBSTRING(s.owner, ca.pos + 2, LEN(s.owner)-ca.pos-2)
FROM (SELECT [GROUP_TASK_IDS] AS owner from MyGroupTasks) s
CROSS APPLY (VALUES(CHARINDEX('=', s.owner))) ca(pos)
后编辑
CROSS APPLY
通常用于根据之前使用的表中的某些条件执行另一个查询。请参阅https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/了解该子句的典型用法。然而,在CROSS APPLY
中,您也可以使用VALUES
子句(而不是SELECT
子查询)。ca(pos)
是分配给子查询和结果列的别名。
SELECT [taskId]= LEFT(s.owner, ca.pos - 1),
[owner] = SUBSTRING(s.owner, ca.pos + 1, 888000)
FROM (SELECT [GROUP_TASK_IDS] AS owner from MyGroupTasks) s
CROSS APPLY (SELECT CHARINDEX('=', s.owner) AS pos) ca
另一种写法(更常用)是:
SELECT LEFT(s.owner, s.pos - 1) AS taskId,
SUBSTRING(s.owner, s.pos + 1, 888000) AS owner
FROM (
SELECT GROUP_TASK_IDS AS owner,
CHARINDEX('=', GROUP_TASK_IDS) AS pos
FROM MyGroupTasks
) s