[英]Need Help to Optimize SQL Query
i'm having a sql master table CHANNEL_PT
which i want to fill based on two other master tables CHANNEL
and PT
. 我有一个SQL主表
CHANNEL_PT
,我想根据其他两个主表CHANNEL
和PT
进行填充。
the CHANNEL_PT
cosist of three colums CHANNEL_PT_CD
, CHANNEL_CD
and PT_CD
. 在
CHANNEL_PT
三个colums cosist CHANNEL_PT_CD
, CHANNEL_CD
和PT_CD
。
the scenario to insert records into CHANNEL_PT
is such that, if i am having two entries in the CHANNEL
table, 将记录插入
CHANNEL_PT
的方案是,如果我在CHANNEL
表中有两个条目,
and two entries in PT
table as below, PT
表中的两个条目如下所示,
then the CHANNEL_PT
table would be as below 那么
CHANNEL_PT
表将如下所示
i knew that this can be done with CURSOR
but i'm not using it due to performance concern. 我知道可以使用
CURSOR
来完成此操作,但是由于性能问题,我不使用它。
i have written the query as below to get the expected result but want to know any other more efficient way or optimized query. 我已经编写了如下查询以获得预期结果,但想知道任何其他更有效的方法或优化的查询。
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;
It sounds like you are describing a cross join. 听起来您正在描述交叉连接。 Is column CHANNEL_PT_CD defined as an IDENTITY column?
CHANNEL_PT_CD列是否定义为IDENTITY列? That removes the need for you to assign that value since the server will do it for you.
这样一来,您便无需分配该值,因为服务器将为您完成该操作。
Then you can do a simple INSERT/SELECT 然后您可以执行简单的INSERT / SELECT
INSERT INTO CHANNEL_PT
SELECT b.CHANNEL_CD, c.PT
FROM CHANNEL b
cross join PT c
Please try: 请试试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.