如何在sql列中溢出字符串并将其存储在基于字符串长度的其他列中

问题描述

我在存储过程中声明了一个临时表,其中有四列地址 例如 AddressLine1、AddressLine2、AddressLine3、AddressLine4,每个都有长度 Varchar(50)

我想从现有表中插入临时表中的数据,以便现有表将地址存储在 AddressLine1 中 所以我想将 AddressLine1 中的地址从现有表插入到临时表但如果地址超过 50 的长度并带有空格,那么我想将剩余地址插入到 AddressLine2 等等

所以总的来说,我想根据列的长度来划分地址,即 50,然后将其存储在 临时表中的addressLine1,addressLine2,addressLine3,addressLine4

select DATALENGTH(ADDRESSLINE1)
from PASSENGER
where DATALENGTH(ADDRESSLINE1) > 50

解决方法

您可以通过一些递归的 cte 和子字符串来实现这一点...遵循一个快速示例,该示例肯定可以优化/缩短,但应该清楚这一点:

DECLARE @x NVARCHAR(200) = N'This is some test and this still is the test and yet here the test continues and so on until the test is finished';

WITH cte1 AS(
-- evaluate all positions of spaces
SELECT @x as txt,CHARINDEX(' ',@x) as idx
UNION ALL
SELECT txt,txt,idx+1) as idx
  FROM cte1
  WHERE CHARINDEX(' ',idx+1) >0
),cte2 AS(
-- evaluate groups basing of the length of 50 as desired output length
SELECT *,idx/50 - CASE WHEN idx%50 = 0 THEN 1 ELSE 0 END AS dividx
  FROM cte1
),cte3 AS(
-- evaluate max space position per group
SELECT txt,dividx,max(idx) maxIdx
  FROM cte2
  GROUP BY txt,dividx
),cte4 AS(
-- evaluate required start and end position for substring operation
SELECT txt,ISNULL(LAG(maxIdx) OVER (PARTITION BY txt ORDER BY dividx)+1,1) AS minIdx,CASE WHEN LEAD(maxIdx) OVER (PARTITION BY txt ORDER BY dividx) IS NULL THEN len(txt) ELSE maxIdx END AS maxIdx
  FROM cte3
)
-- perform substring
SELECT SUBSTRING(txt,minIdx,maxIdx-minIdx+1) AS txt
  FROM cte4
  OPTION (MAXRECURSION 0)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...