我有一个内部查询,在外面引用如下。
第一种情况与预期相符,但第二种情况失败。第二种情况有没有解决方法?
我有一个类似的设置,我需要内部查询结果集以便稍后进行调试。
首先情况
select * from
(select 1 col1 ) tb1
第二情况
select * from
(select 1 col1 into x_table) tb1
答案 0 :(得分:1)
您可以尝试以下解决方案之一:
SET NOCOUNT ON;
GO
CREATE TABLE dbo.MyTable(
EntryDate DATE NOT NULL,
Emptied BIT NOT NULL
);
GO
INSERT INTO dbo.MyTable (EntryDate,Emptied)
VALUES
('2013-01-01',0),
('2013-01-02',0),
('2013-01-03',1);
-- Solution #1 (SQL2005+)
DECLARE @Output1 TABLE(
EntryDate DATE NOT NULL,
Emptied BIT NOT NULL
);
INSERT INTO dbo.MyTable (EntryDate,Emptied)
OUTPUT inserted.* INTO @Output1(EntryDate,Emptied)
SELECT '2013-01-04',0
UNION ALL
SELECT '2013-01-05',0;
PRINT 'Solution #1: @Output1 content'
SELECT * FROM @Output1;
-- Solution #2 (SQL2008+)
DECLARE @Output2 TABLE(
EntryDate DATE NOT NULL,
Emptied BIT NOT NULL
);
INSERT INTO @Output2(EntryDate,Emptied)
SELECT *
FROM
(
INSERT INTO dbo.MyTable (EntryDate,Emptied)
OUTPUT inserted.*
VALUES
('2013-01-06',1),
('2013-01-07',0),
('2013-01-08',0),
('2013-01-09',1)
)x
PRINT 'Solution #2: @Output2 content'
SELECT * FROM @Output2;
结果:
/*
Solution #1: @Output1 content
EntryDate Emptied
---------- -------
2013-01-04 0
2013-01-05 0
Solution #2: @Output2 content
EntryDate Emptied
---------- -------
2013-01-06 1
2013-01-07 0
2013-01-08 0
2013-01-09 1
*/