我对CTEs
,temp
表格进行了一次非常大的查询,并且我希望将其放入IF
和ELSE
块中,因为它们具有不同的条件对于他们两个,取决于参数。简化后如下所示:
DECLARE @parameter varchar(15)
If(OBJECT_ID('tempdb..#table1') Is Not Null)
Begin
Drop Table #table1
End
create table #table1
(
column1
column2
column3
)
If(OBJECT_ID('tempdb..#table2') Is Not Null)
Begin
Drop Table #table2
End
create table #table2
(
column1
column2
column3
)
IF @parameter = 'Option1' BEGIN
select * from (
INSERT INTO #table1
select * from... where 'condition_for_Option1'
INSERT INTO #table2
select * from... where 'condition_for_Option1'
select * from #table1
union all
select * from #table2) as DATA
END ELSE
IF @parameter = 'Option2' BEGIN
SELECT *
FROM
(
INSERT INTO #table1
select * from... where 'condition_for_Option2'
INSERT INTO #table2
select * from... where 'condition_for_Option2'
select * from #table1
union all
select * from #table2)
as DATA
END
我把#temp
表放在开头,它修复了一部分问题,但我仍然有:
Msg 156,Level 15,State 1,Line 31
关键字' INSERT'附近的语法不正确 Msg 102,Level 15,State 1,Line 37
')'附近的语法不正确 Msg 156,Level 15,State 1,Line 48
关键字' INSERT'附近的语法不正确 Msg 102,Level 15,State 1,Line 54
')附近的语法不正确'。
这是如何使这项工作的?
答案 0 :(得分:4)
insert
声明中不能包含select
声明。 Actualy你可以改写:
IF @parameter = 'Option1'
BEGIN
INSERT INTO #table1
SELECT * FROM... WHERE 'condition_for_Option1'
INSERT INTO #table2
SELECT * FROM... WHERE 'condition_for_Option1'
SELECT * FROM #table1
UNION ALL
SELECT * FROM #table2
END
ELSE IF @parameter = 'Option2'
BEGIN
INSERT INTO #table1
SELECT * FROM... WHERE 'condition_for_Option2'
INSERT INTO #table2
SELECT * FROM... WHERE 'condition_for_Option2'
SELECT * FROM #table1
UNION ALL
SELECT * FROM #table2
END
但我在这里看不到临时表的任何用法,所以你可以重写:
IF @parameter = 'Option1'
BEGIN
SELECT * FROM... WHERE 'condition_for_Option1'
UNION ALL
SELECT * FROM... WHERE 'condition_for_Option1'
END
ELSE IF @parameter = 'Option2'
BEGIN
SELECT * FROM... WHERE 'condition_for_Option2'
UNION ALL
SELECT * FROM... WHERE 'condition_for_Option2'
END
答案 1 :(得分:1)
为什么不呢?
IF @parameter = 'Option1' BEGIN
INSERT INTO #table1
select * from... where 'condition_for_Option1'
INSERT INTO #table2
select * from... where 'condition_for_Option1'
select * from (
select * from #table1
union all
select * from #table2) as DATA
END
ELSE
IF @parameter = 'Option2' BEGIN
INSERT INTO #table1
select * from... where 'condition_for_Option2'
INSERT INTO #table2
select * from... where 'condition_for_Option2'
SELECT *
FROM
(
select * from #table1
union all
select * from #table2)
as DATA
END