我有一个存储过程,其中在两个表上插入查询。
masters_table,child_table
如您所见@Value1,@Value2,@Value3,@Value4
有参数。我已经为每个块写了insert语句,我可以在这里使用循环来避免每个块的多次插入写入,假设我有第n个值然后我必须编写第n次块顺式插入查询,任何更好的方法来实现这个任务
Create proc sp_insert_master_child
(
@Details_Data custom_tb READONLY,
@Value1 nvarchar(500),
@Value2 nvarchar(500),
@Value3 nvarchar(500),
@Value4 nvarchar(500),
@Value5 nvarchar(500),
@Value6 nvarchar(500),
@Value7 nvarchar(500)
)
as begin
declare @id bigint
------- block 1
if @Value1 is not null
begin
insert into masters_table (col1,col2,col3))
select Substring(@Value1, 1,Charindex(',', @Value1)-1) as col_value_1,
Substring(@Value1, Charindex(',', @Value1)+1, LEN(@Value1)) as col_value_2
select @id = @@IDENTITY
insert into child_table (col1,col2,col3)
SELECT @id,col_val_2,col_val_3 FROM @Details_Data WHERE blockType='blk_1';
end
------ block 2
if @Value2 is not null
begin
insert into masters_table (col1,col2,col3))
select Substring(@Value2, 1,Charindex(',', @Value2)-1) as col_value_1,
Substring(@Value2, Charindex(',', @Value2)+1, LEN(@Value2)) as col_value_2
select @id = @@IDENTITY
insert into child_table (col1,col2,col3)
SELECT @id,col_val_2,col_val_3 FROM @Details_Data WHERE blockType='blk_2';
end
------ block 3
if @Value3 is not null
begin
insert into masters_table (col1,col2,col3))
select Substring(@Value3, 1,Charindex(',', @Value3)-1) as col_value_1,
Substring(@Value3, Charindex(',', @Value2)+1, LEN(@Value3)) as col_value_2
select @id = @@IDENTITY
insert into child_table (col1,col2,col3)
SELECT @id,col_val_2,col_val_3 FROM @Details_Data WHERE blockType='blk_3';
end
------ block 4
.......
------ block 5
.......
答案 0 :(得分:0)
您可以将所有参数插入到表中。使用while循环并从表中逐行读取(参数)。
例如:
declare @x int
set @x= 1
declare @tmp table ( val int )
while (@x < noofrows)
begin
***********
Use Top @x value to get row(parameter in your case) from table
perform your operation
*************
increment x(set @X=@x+1)
end