根据 MSSQL 中不同 table 中列的值在 table 中插入一行
Inserting a row in a table depending on the values of columns in a different table in MSSQL
我有一个 table 叫做 reportValues:
id isNew isExclusive isPremium
10 1 1 0
11 0 0 1
12 1 0 1
我有一个名为 productProperties
的 table
isNew 的 propertyId 为 1,isExclusive 的 propertyId 为 2,isPremium 的 propertyId 为 3。
id propertyId
10 1
10 2
11 3
12 1
12 3
我需要根据 table reportValues 的布尔值将行添加到 productProperties,如何使用存储过程执行此操作?我认为您需要某种 if 语句,但我找不到示例。
我想你正在寻找这样的东西。使用 CROSS APPLY
并分配 1,2,3 属性Id 对布尔值进行反透视。然后插入转换后的值 WHERE
布尔值 属性 是 TRUE
,即 v.property=1。以下存储过程插入 productProperties table 并检查以确保值不存在。也许那没有必要?可以注释掉或删除。
drop proc if exists dbo.productPropertiesInsert;
go
create proc dbo.productPropertiesInsert
as
set nocount on;
insert productProperties
select v.id, v.propertyId
from reportValues rv
cross apply (values (1, rv.id, rv.isNew),
(2, rv.id, rv.isExclusive),
(3, rv.id, rv.isPremium))
v(propertyId, id, property)
where v.property=1
/* optional code? */
and not exists(select 1
from productProperties p_in
where v.id=p_in.id
and v.propertyId=p.propertyId);
go
我有一个 table 叫做 reportValues:
id isNew isExclusive isPremium
10 1 1 0
11 0 0 1
12 1 0 1
我有一个名为 productProperties
的 tableisNew 的 propertyId 为 1,isExclusive 的 propertyId 为 2,isPremium 的 propertyId 为 3。
id propertyId
10 1
10 2
11 3
12 1
12 3
我需要根据 table reportValues 的布尔值将行添加到 productProperties,如何使用存储过程执行此操作?我认为您需要某种 if 语句,但我找不到示例。
我想你正在寻找这样的东西。使用 CROSS APPLY
并分配 1,2,3 属性Id 对布尔值进行反透视。然后插入转换后的值 WHERE
布尔值 属性 是 TRUE
,即 v.property=1。以下存储过程插入 productProperties table 并检查以确保值不存在。也许那没有必要?可以注释掉或删除。
drop proc if exists dbo.productPropertiesInsert;
go
create proc dbo.productPropertiesInsert
as
set nocount on;
insert productProperties
select v.id, v.propertyId
from reportValues rv
cross apply (values (1, rv.id, rv.isNew),
(2, rv.id, rv.isExclusive),
(3, rv.id, rv.isPremium))
v(propertyId, id, property)
where v.property=1
/* optional code? */
and not exists(select 1
from productProperties p_in
where v.id=p_in.id
and v.propertyId=p.propertyId);
go