我正在使用SQL Server,我有2个存储过程:
第一个存储过程:
CREATE PROCEDURE A
AS
SELECT DISTINCT
TC.*, MS.*
FROM
VIEW1 TC,
View2 MS
WHERE
TC.ID = MS.ID
ORDER BY
TC.Type ASC
第二个存储过程:
CREATE PROCEDURE B
AS
SET NOCOUNT ON
SELECT DISTINCT
TC.*, MS.*
FROM
VIEW3 TC,
VIEW2 MS
WHERE
C.ID = MS.ID
ORDER BY
MS.Date DESC
我想获取这两个存储过程的数据结果,然后将其绑定到gridview。我创建了以下存储过程,但它抛出了ID列无效的错误:
CREATED PROCEDURE C
AS
SET NOCOUNT ON
SELECT DISTINCT
TC.*, MS.*
FROM
(VIEW1 TC
LEFT JOIN
VIEW2 MS ON MS.ID = TC.ID)
UNION
SELECT DISTINCT
TC1.*, MS.*
FROM
(VIEW3 TC1
LEFT JOIN
VIEW2 MS on MS.ID = TC1.ID)
如何组合2个存储过程的数据结果?仅供参考,所有列都是从视图中选择的,而不是表格。
答案 0 :(得分:2)
在存储过程编号3中,您使用的是括号错误,它应该是这样的
CREATE PROCEDURE C
AS
SELECT DISTINCT
TC.*, MS1.*
FROM
VIEW1 TC
LEFT JOIN
VIEW2 MS1 ON MS1.ID = TC.ID
UNION
SELECT DISTINCT
TC2.*, MS2.*
FROM
VIEW3 TC2
LEFT JOIN
VIEW2 MS2 on MS2.ID = TC2.ID
您还可以将存储过程的结果插入临时表,然后显示临时表的结果:
CREATE TABLE #tempA(Column1 NVARCHAR(50),Column2 NVARCHAR(50),...)
INSERT INTO #tempA ( Column1, Column2, ... )
EXEC A
INSERT INTO #tempA (Column1, Column2, ...)
EXEC B
SELECT * FROM #tempA
答案 1 :(得分:0)
如果您不想复制代码,请创建一个结果表,如
CREATE PROCEDURE C
AS
CREATE TABLE #foo (bar int ...)
INSERT INTO #foo EXEC A
INSERT INTO #foo EXEC B
SELECT * FROM #foo
DROP TABLE #foo
如果列具有相似的数据类型,则只需单击查询
CREATE PROCEDURE C
AS
SELECT A.* FROM
(
SELECT DISTINCT
TC.*, MS.*
FROM
VIEW1 TC,
View2 MS
WHERE
TC.ID = MS.ID
ORDER BY
TC.Type ASC
) A
UNION ALL
SELECT B.* FROM
(
SELECT DISTINCT
TC.*, MS.*
FROM
VIEW3 TC,
VIEW2 MS
WHERE
C.ID = MS.ID
ORDER BY
MS.Date DESC
) B