0

我有一个 sql 主表CHANNEL_PT ,我想根据其他两个主表CHANNELPT.

三列的CHANNEL_PTcosistCHANNEL_PT_CD和.CHANNEL_CDPT_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;
4

2 回答 2

1

听起来您正在描述交叉连接。列 CHANNEL_PT_CD 是否定义为 IDENTITY 列?这消除了您分配该值的需要,因为服务器会为您执行此操作。

然后你可以做一个简单的 INSERT/SELECT

INSERT INTO CHANNEL_PT
SELECT b.CHANNEL_CD, c.PT
  FROM CHANNEL b 
 cross join PT c
于 2013-11-01T05:26:43.227 回答
0

请试试:

DECLARE @CPT INT=0;
SELECT @CPT = ISNULL(MAX(CHANNEL_PT_CD),0) FROM CHANNEL_PT

INSERT INTO CHANNEL_PT
SELECT DISTINCT @CPT+ROW_NUMBER() OVER(ORDER BY b.CHANNEL_CD),
     b.CHANNEL_CD, 
     c.PT
FROM CHANNEL b, PT c
WHERE (SELECT COUNT(*) FROM CHANNEL_PT a 
       WHERE a.CHANNEL_CD=b.CHANNEL_CD AND a.PT_CD=c.PT)=0
于 2013-11-01T05:18:15.650 回答