在表transact-SQL中插入未计算的Id
我有一个存储过程,从C中的API接收JSON数据。我将数据插入两个表中,如下所示:在表transact-SQL中插入未计算的Id,sql,sql-server,tsql,stored-procedures,Sql,Sql Server,Tsql,Stored Procedures,我有一个存储过程,从C中的API接收JSON数据。我将数据插入两个表中,如下所示: INSERT INTO dbo.ServiceRequestHeader(SubscriptionId, CustomerAccountId, ModifiedBy) OUTPUT Inserted.ServiceRequestHeaderId INTO @TempT SELECT SubscriptionId, CustomerAccountId, Mod
INSERT INTO dbo.ServiceRequestHeader(SubscriptionId, CustomerAccountId, ModifiedBy)
OUTPUT Inserted.ServiceRequestHeaderId INTO @TempT
SELECT
SubscriptionId,
CustomerAccountId,
ModifiedBy
FROM
OpenJson(@JsonServiceRequest)
WITH
(SubscriptionId TinyInt,
CustomerAccountId Int)
SELECT @TempId = Id FROM @TempT
INSERT INTO dbo.ServiceRequest(ServiceRequestId, ServiceRequestHeaderId, SubscriptionId)
SELECT
@TempId, -- <= Here I need to modify the serviceRequestHeaderId
@TempId,
SubscriptionId
FROM
OpenJson(@JsonServiceRequest, '$.ServiceRequest')
WITH (SubscriptionId TinyInt,
...)
问题是serviceRequestId不是一个计算字段,它是一个特殊情况,取决于ServiceRequestHeaderId
例如:
如果ServiceRequestHeaderId=1000,ServiceRequestId将为1000 001、1000 002。。。N
这就是我无法找到解决方法的地方使用CTE计算每个请求的行号,然后根据它构建id,例如
with MyCTE as (
select
SubscriptionId
-- Order by whatever makes business sense to you
, row_number() over (order by SubscriptionId) rn
from openjson(@JsonServiceRequest, '$.ServiceRequest')
with (
SubscriptionId tinyint,
...
)
)
insert into dbo.ServiceRequest (ServiceRequestId, ServiceRequestHeaderId, SubscriptionId)
-- Put whatever logic you like here to calculate a row number based id
select convert(varchar(4),@TempId) + ' ' + case when rn >= 100 then convert(varchar(3),rn) when rn > 10 then '0' + convert(varchar(2),rn) else '00' + convert(varchar(1),rn) end
, @TempId, SubscriptionId
from MyCTE;
使用CTE计算每个请求的行号,然后根据它生成id,例如
with MyCTE as (
select
SubscriptionId
-- Order by whatever makes business sense to you
, row_number() over (order by SubscriptionId) rn
from openjson(@JsonServiceRequest, '$.ServiceRequest')
with (
SubscriptionId tinyint,
...
)
)
insert into dbo.ServiceRequest (ServiceRequestId, ServiceRequestHeaderId, SubscriptionId)
-- Put whatever logic you like here to calculate a row number based id
select convert(varchar(4),@TempId) + ' ' + case when rn >= 100 then convert(varchar(3),rn) when rn > 10 then '0' + convert(varchar(2),rn) else '00' + convert(varchar(1),rn) end
, @TempId, SubscriptionId
from MyCTE;
您可以生成ServiceRequestId,如下所示。我使用000的格式函数来填充0到3位数字。如果需要四位数字,请使用0000 从@test中选择@TempId=Id 插入到dbo.serviceRequestId、ServiceRequestHeaderId、SubscriptionId中 选择
CONCAT@TempId,FORMATROW_NUMBER OVERORDER通过选择null,'000'作为ServiceRequestId,-您可以生成ServiceRequestId,如下所示。我使用000的格式函数来填充0到3位数字。如果需要四位数字,请使用0000 从@test中选择@TempId=Id 插入到dbo.serviceRequestId、ServiceRequestHeaderId、SubscriptionId中 选择
CONCAT@TempId,FORMATROW_NUMBER OVERORDER BY SELECT null,'000'作为ServiceRequestId,-此SELECT@TempId=Id From@test意味着您一次只能插入一个服务请求头?是这样吗?是的,只有一个服务请求头,但多个服务请求从@TELT中选择@TempId=Id意味着您一次只能插入一个服务请求头?是这样吗?是的,只有一个服务请求头,但有多个服务请求