如何调用在视图中返回数据的存储过程?这甚至可能吗?
SQL Server中不允许这种结构.内联表值函数可以作为参数化视图执行,但仍然不允许像这样调用SP.
以下是交替使用SP和内联TVF的一些示例 - 您将看到TVF更灵活(它基本上更像是一个视图而不是一个功能),因此在可以使用内联TVF的情况下,它们可以更多地重新使用eusable:
CREATE TABLE dbo.so916784 ( num int ) GO INSERT INTO dbo.so916784 VALUES (0) INSERT INTO dbo.so916784 VALUES (1) INSERT INTO dbo.so916784 VALUES (2) INSERT INTO dbo.so916784 VALUES (3) INSERT INTO dbo.so916784 VALUES (4) INSERT INTO dbo.so916784 VALUES (5) INSERT INTO dbo.so916784 VALUES (6) INSERT INTO dbo.so916784 VALUES (7) INSERT INTO dbo.so916784 VALUES (8) INSERT INTO dbo.so916784 VALUES (9) GO CREATE PROCEDURE dbo.usp_so916784 @mod AS int AS BEGIN SELECT * FROM dbo.so916784 WHERE num % @mod = 0 END GO CREATE FUNCTION dbo.tvf_so916784 (@mod AS int) RETURNS TABLE AS RETURN ( SELECT * FROM dbo.so916784 WHERE num % @mod = 0 ) GO EXEC dbo.usp_so916784 3 EXEC dbo.usp_so916784 4 SELECT * FROM dbo.tvf_so916784(3) SELECT * FROM dbo.tvf_so916784(4) DROP FUNCTION dbo.tvf_so916784 DROP PROCEDURE dbo.usp_so916784 DROP TABLE dbo.so916784
exec sp_addlinkedserver @server = 'local', @srvproduct = '', @provider='SQLNCLI', @datasrc = @@SERVERNAME go create view ViewTest as select * from openquery(local, 'sp_who') go select * from ViewTest go
我能够在视图中调用存储过程(SQL Server 2005).
CREATE FUNCTION [dbo].[dimMeasure] RETURNS TABLE AS ( SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost; Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2') ) RETURN GO
在内存存储过程中我们需要设置:
set nocount on SET FMTONLY OFF
CREATE VIEW [dbo].[dimMeasure] AS SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2') GO