我正在编写一个存储过程来获取TableA中的记录列表,并将这些记录插入到TableB中。现在我面临着这个问题。
这是我的sp:
USE [Sample_DB]
GO
SET ANSI_NULLS ON
GOenter code here
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddStoredProcedure]
AS
BEGIN
DECLARE @ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO @ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id)+1 from [TableA] where MaritalStatus='Male'),4),' ','0') as varchar)),Name,MaritalStatus FROM @ProcessedData
END
TableA contains,
Id Name MaritalStatus
1 John Male
2 Sam Male
3 Seema Female
当我执行存储过程时,AddStoredProcedure
我的输出为
TableB contains,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0003 Sam Male
但我需要如下;
TableB should be,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0004 Sam Male
提前感谢大家的回复。
答案 0 :(得分:1)
您可以将row_number函数用作:
DECLARE @ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO @ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
DECLARE @IdMax int;
SELECT @IdMax = MAX(Id)
FROM [TableA]
WHERE MaritalStatus='Male';
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((row_number() over(Order by Name)+@IdMax ),4),' ','0') as varchar)),
Name,MaritalStatus
FROM @ProcessedData
答案 1 :(得分:0)
DECLARE @TableA TABLE (Id INT, Name VARCHAR(20), MaritalStatus VARCHAR(6))
DECLARE @TableB TABLE (Id VARCHAR(9), Name VARCHAR(20), MaritalStatus VARCHAR(6))
INSERT INTO @TableA (Id, Name, MaritalStatus)
VALUES
(1, 'John', 'Male'),
(2, 'Sam', 'Male'),
(3, 'Seema', 'Female')
DECLARE @ProcessedData AS TABLE (Id INT IDENTITY(1,1), Name varchar(200),MaritalStatus varchar(200))
INSERT INTO @ProcessedData (Name ,MaritalStatus )
SELECT Name
,MaritalStatus
FROM @TableA
WHERE MaritalStatus='Male'
INSERT INTO @TableB (Id, Name, MaritalStatus)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id) from @TableA where MaritalStatus='Male')+Id,4),' ','0') as varchar))
,Name
,MaritalStatus
FROM @ProcessedData
SELECT * FROM @TableB
我已经用表变量替换了你的表,所以它可以直接运行。 你有什么理由想从0003开始吗?无论如何,此查询将生成所需的输出,如果需要更改,请进行注释。