[英]Stored procedure in SQL Server 2012
I need your help in writing a stored procedure to update the data given below into a table in SQL Server. 在编写存储过程以将下面给出的数据更新到SQL Server中的表中时,我需要您的帮助。
I have uploaded a picture to ensure format is set right. 我已上传图片以确保格式正确。
The second column which identifies the part number, example: part 100
has 103
and 104
as its components in bill of materials. 标识零件号的第二列,例如: part 100
在物料清单中具有103
和104
作为其组件。 However only 1 (either 103 is allocated to id 1
, part 100
or 104
is allocated to id 2
, part 100
). 但是,仅1(将103分配给id 1
, part 100
或104
分配给id 2
, part 100
)。
For us to differentiate during the planning bill of materials for the top level assembly, we need to update assembly hashkey (string) with the last character of component used (ex: 103
, use 3
), 000111
becomes 300111
. 为了使我们在顶层装配的计划物料清单中有所区别,我们需要使用所用零部件的最后一个字符(例如: 103
,使用3
)更新装配体哈希键(字符串), 000111
变为300111
。 Doesn't matter which component gets assigned to the parent. 哪个组件分配给父级无关紧要。
Can anybody please help me with this. 有人可以帮我吗 thanks. 谢谢。
Data Structure Expected result
ID Part hashkey ID Part hashkey
----------------- --------------------
1 100 000111 1 100 300111
2 100 000111 2 100 400111
3 103 000111 3 103 000111
4 104 000111 4 104 000111
Data structure: expected_result 数据结构: expected_result
Try This. 尝试这个。
DECLARE @data TABLE (ID INT, Part INT, hashkey VARCHAR(100))
INSERT INTO @data
SELECT 1, 100, '000111'
UNION ALL
SELECT 2, 100, '000111'
UNION ALL
SELECT 3, 101, '000111'
UNION ALL
SELECT 4, 102, '000111';
WITH cte
AS (
SELECT ID, Part, hashkey, ROW_number() OVER (
PARTITION BY part ORDER BY part ASC
) AS RN
FROM @data
)
SELECT ID, Part, CASE
WHEN RN > 1
THEN cast(ID AS VARCHAR) + hashkey
WHEN lead(RN, 1) OVER (
ORDER BY part, RN
) > 1
THEN cast(ID AS VARCHAR) + hashkey
ELSE hashkey
END AS hashkey
FROM cte
Ok, if I understand your requirement now, then this should do it: 好的,如果我现在理解您的要求,那么应该这样做:
WITH cteParent AS (
SELECT Id, hashkey,
ROW_NUMBER() OVER (Partition By hashkey, Order by ID) AS rn
FROM MyTable
WHERE Part=100
)
, cteComponent AS (
SELECT Id, hashkey,
ROW_NUMBER() OVER (Partition By hashkey, Order by ID) AS rn
FROM MyTable
WHERE Part<>100
)
SELECT t.Id, t.Part
, CASE
WHEN t.Part=100 THEN RIGHT(CAST(c.Part AS varchar(31)),1) + SUBSTRING(CAST(p.hashkey AS varchar(31)), 2, LEN(CAST(t.hashkey AS varchar(31)))-1)
ELSE CAST(t.hashkey AS varchar(31))
END AS hashkey
FROM MyTable t
LEFT OUTER JOIN cteParent p ON t.Id=p.Id
LEFT OUTER JOIN cteComponent c
ON p.hashkey=c.hashkey
AND p.rn=c.rn
ORDER BY ID asc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.