我有一个 sql 主表CHANNEL_PT
,我想根据其他两个主表CHANNEL
和PT
.
三列的CHANNEL_PT
cosistCHANNEL_PT_CD
和.CHANNEL_CD
PT_CD
插入记录的场景CHANNEL_PT
是这样的,如果我在CHANNEL
表中有两个条目,
以及下表中的两个条目PT
,
那么CHANNEL_PT
表格如下
我知道这可以做到,CURSOR
但由于性能问题我没有使用它。
我编写了如下查询以获得预期结果,但想知道任何其他更有效的方式或优化的查询。
BEGIN TRANSACTION
DECLARE @CH INT;
DECLARE @CH_CNT INT;
DECLARE @CH_MAX INT;
SELECT @CH_MAX = MAX(CHANNEL_CD) FROM CHANNEL;
SELECT @CH = ISNULL(MIN(CHANNEL_CD),0),@CH_CNT=COUNT(CHANNEL_CD) FROM CHANNEL WHERE CHANNEL_CD > -1
WHILE @CH <= @CH_MAX
BEGIN
DECLARE @PT INT;
DECLARE @PT_CNT INT;
DECLARE @PT_MAX INT;
SELECT @PT_MAX = MAX(PT_CD) FROM PT;
SELECT @PT = ISNULL(MIN(PT_CD),0),@PT_CNT=COUNT(PT_CD) FROM PT WHERE PT_CD > -1
WHILE @PT <=@PT_MAX
BEGIN
DECLARE @CPT INT;
SELECT @CPT = ISNULL(MAX(CHANNEL_PT_CD),0) FROM CHANNEL_PT
IF NOT EXISTS(SELECT CHANNEL_CD,PT_CD FROM CHANNEL_PT WHERE CHANNEL_CD=@CH and PT_CD=@PT)
BEGIN
INSERT INTO CHANNEL_PT VALUES(@CPT+1,@CH,@PT)
END
SELECT @PT = MIN(PT_CD) FROM PT WHERE PT_CD > @PT
END
SELECT @CH=MIN(CHANNEL_CD) FROM CHANNEL WHERE CHANNEL_CD > @CH
END
COMMIT;