我的存储过程中有以下代码:
CREATE MyProc
AS
CREATE TABLE #Table1
(
Field1 INT NOT NULL,
Field2 VARCHAR NULL,
Field3 VARCHAR NULL,
Field4 VARCHAR NULL
);
-----填充临时表-----
INSERT INTO #Table1 (Field1)
SELECT val1 FROM Tab1
INSERT INTO #Table1 (Field1,Field2)
SELECT val1,"val2" FROM Tab2
INSERT INTO #Table1 (Field1,Field2,Field3)
SELECT val1,"val2","val3" FROM Tab3
INSERT INTO #Table1 (Field1,Field2,Field3,Field4)
SELECT val1,"val2","val3","val4" FROM Tab3
SELECT Field1,Field2,Field3,Field4 FROM #Table1
DROP #Table1
大约有10-15个INSERT语句正在填充临时表。我想调整存储过程以使用CTE或其他方式提高性能。我如何重写该过程?
答案 0 :(得分:0)
我不完全确定这会以任何方式变得更好但是这是使用cte来获得相同的输出(我使用了一些lazy-ass值数组来使它开箱即用,你可以用实际的表来代替那些):
with cte (f1, f2, f3, f4)
as (
select 1, null, null, null
from (
values (1)
) t1(n1)
union all
select 1, 2, null, null
from (
values (1, 2)
) t1(n1, n2)
union all
select 1, 2, 3, null
from (
values (1, 2, 3)
) t1(n1, n2, n3)
union all
select 1, 2, 3, 4
from (
values (1, 2, 3, 4)
) t1(n1, n2, n3, n4)
)
select *
from cte