我有一個sql主表CHANNEL_PT
我想填寫基於其他兩個主表CHANNEL
和PT
。需要幫助來優化SQL查詢
the CHANNEL_PT
cosist of three colums CHANNEL_PT_CD
,CHANNEL_CD
and 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 <[email protected]_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 [email protected] and [email protected])
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;
光標是在大多數情況下比基於集合的運算慢。但你用一個更慢的while循環替換遊標。 – adrianm