表格' S :
CREATE TABLE Test_01
(
Cola VARCHAR(MAX),
Colb VARCHAR(MAX)
);
INSERT INTO Test_01 VALUES(1,'A');
CREATE TABLE Test_02
(
Cola VARCHAR(MAX),
Colb VARCHAR(MAX)
);
INSERT INTO Test_02 VALUES(2,'B');
CREATE TABLE Test_03
(
Cola VARCHAR(MAX),
Colb VARCHAR(MAX)
);
INSERT INTO Test_01 VALUES(3,'C');
查看:
CREATE VIEW View_Test AS
SELECT * FROM Test_01 UNION ALL
SELECT * FROM Test_02 UNION ALL
SELECT * FROM Test_03 UNION ALL;
记录:
SELECT * FROM dbo.View_test
Cola Colb
------------------
1 A
2 B
3 C
注意:现在我想通过将Cola
值传递给商店流程来准备临时视图。
示例:如果我将值1
传递给存储过程,那么它应该准备一个临时视图
使用表test_01
,因为记录1
属于表test_01
。
如果我将值1,2,3
传递给存储过程,那么它应该准备一个临时视图
使用表格test_01,test_02,test_03
,因为记录1,2,3
属于表格test_01,test_02,test_03
。
对于上述要求,我编写了以下存储过程:
存储过程:
ALTER PROCEDURE sp_Test_90
@Cola varchar(MAX)
AS
DECLARE @SQL VARCHAR(MAX)
DECLARE @Tab VARCHAR(MAX)
DECLARE @Query VARCHAR(MAX)
DECLARE Cur CURSOR FAST_FORWARD FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEW_TABLE_USAGE
WHERE VIEW_NAME = 'View_Test'
OPEN Cur
FETCH NEXT FROM Cur INTO @Tab
WHILE(@@FETCH_STATUS=0)
BEGIN
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
BEGIN
DROP TABLE #Temp
END
CREATE TABLE #Temp
(
ColaValues VARCHAR(MAX)
);
SET @SQL = 'INSERT INTO #Temp(ColaValues) SELECT DISTINCT Cola FROM ['+@Tab+'] WHERE Cola IN('''+REPLACE(@Cola,',',''',''')+''')';
PRINT(@SQL);
EXECUTE(@SQL);
----------------------
/*Got Stuck HERE*/
----------------------
IF (SELECT DISTINCT colavalues FROM #Temp) IN(''''+REPLACE(@Cola,',',''',''')+'''')---IN (@Cola) -------GOT STUCK HERE
BEGIN
SET @SQL +='SELECT * FROM ['+@Tab+'] UNION ALL';
END
FETCH NEXT FROM Cur INTO @Tab
END
CLOSE Cur;
DEALLOCATE Cur;
SET @Query = 'WITH CTE
AS
(
'+@SQL+'
)
SELECT * FROM CTE';
PRINT(@Query);
EXECUTE(@Query);
GO
但是卡在if条件下检查给定参数中是否存在Cola值。
答案 0 :(得分:1)
您不想要临时视图。您需要一个内联表值函数:
create function udf_myview (
@cola varchar(max)
)
returns table
as
return(select *
from dbo.View_Test
where cola = @cola
);
然后您可以将其称为:
select *
from dbo.udf_myview('XYZ');