我在SQL表中有一列。列是“水坝”
SELECT
FROM (
SELECT DISTINCT First_Name FROM t
) AS emp
CROSS JOIN (VALUES
('January'), ('February'), ('March'), ('April'), ('May'), ('June'),
('July'), ('August'), ('September'), ('October'), ('November'), ('December')
) mon(Month_Name)
LEFT JOIN t ON emp.First_Name = t.First_Name AND mon.Month_Name = t.Month_Name
WHERE t.PK IS NULL
对于该列中的大多数数据,其格式如下:
马拉松内拉(Jpn)1942
我想更新数据库以将列分为三部分
SELECT Dam
FROM [dbo].[names]
偶尔/很少我在该字段中只有Dam_Name值,并且没有(用作分隔符。在这种情况下,我希望Dam_Name保持原样,而Dam_Country和Dam_YOB为NULL >
我看过PARSENAME,但是我不确定如果有更有效的方法来更新数据库,该如何构造。
任何帮助表示赞赏
答案 0 :(得分:0)
可以使用XML技巧来做到这一点:
;WITH splitValues AS
(
SELECT id,
LTRIM(RTRIM(m.n.value('.[1]', 'varchar(8000)'))) AS splitValue,
CASE ROW_NUMBER()OVER (PARTITION BY id ORDER BY id) WHEN 1 THEN 'Name' WHEN 2 THEN 'Country' ELSE 'YOB' end AS columnHeader
FROM
(
SELECT id,
CAST('<XMLRoot><RowData><ColumnData>'
+ REPLACE(REPLACE(string, '(', '</ColumnData><ColumnData>'), ')', '</ColumnData><ColumnData>')
+ '</ColumnData></RowData></XMLRoot>' AS XML) AS xmlString
FROM #x
) xmlTable
CROSS APPLY xmlString.nodes('/XMLRoot/RowData/ColumnData') m(n))
This gives you results like:
========================
id splitValue columnHeader
1 Marathon Nella Name
1 Jpn Country
1 1942 Year
下一步更新表格:
UPDATE table
SET Name = splitValue
From table INNER JOIN
splitValues ON table.Id = splitValues.Id AND columnHeader = 'Name'
等
答案 1 :(得分:-1)
嗯,在SQL Server中字符串提取不是那么容易。假设国家是三个字符:
select left(dam, charindex('(', dam + ' (') - 2) as name,
nullif(left(stuff(dam, 1, charindex('(', dam + '('), ''), 3), '') as country,
nullif(stuff(dam, 1, charindex(')', dam + ')'), ''), '') as dob
from (values ('Marathon Nella (Jpn)1942'), ('testing a')) v(dam)
如果这些条件不成立,可以对此进行调整,但这可以使您知道如何做。
Here是db <>小提琴。