今天遇到一个问题,需要用到视图显示内容,
但是内容需要用存储过程获取,
网上找了半天发现有一个方法可以查询存储过程内容,
但是存储过程里不可以做 Insert /Update /Insert
如果存储过程没有这些功能,
那select * from (存储过程) 会有什么作用呢?
if OBJECT_ID('sp_testsp','P') is not null drop proc sp_testsp
go
--创建sp
create proc sp_testsp
as
declare @i int
set @i=50
select 1 as id ,'evan' as dcname
--select * from @tb
go
--开启 Ad Hoc Distributed Queries
exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'ad Hoc Distributed Queries',1
reconfigure
go
--查询存储过程返回内容
/*
存储过程里不允许有 update /Delete / insert
*/
select * from openrowset('sqloledb','Trusted_Connection=yes','exec test_testsp')
go
但是内容需要用存储过程获取,
网上找了半天发现有一个方法可以查询存储过程内容,
但是存储过程里不可以做 Insert /Update /Insert
如果存储过程没有这些功能,
那select * from (存储过程) 会有什么作用呢?
if OBJECT_ID('sp_testsp','P') is not null drop proc sp_testsp
go
--创建sp
create proc sp_testsp
as
declare @i int
set @i=50
select 1 as id ,'evan' as dcname
--select * from @tb
go
--开启 Ad Hoc Distributed Queries
exec sp_configure 'show advanced options',1
reconfigure
exec sp_configure 'ad Hoc Distributed Queries',1
reconfigure
go
--查询存储过程返回内容
/*
存储过程里不允许有 update /Delete / insert
*/
select * from openrowset('sqloledb','Trusted_Connection=yes','exec test_testsp')
go
首先存储过程仅仅是一个封装的过程。里面的内容,insert update delete 都是可以做的。
其次,存储过程直接输出的结果集,可以用于前台显示。(不太明白lz说的必须用视图?是个什么情况)
2. 创建相同架构的临时表或者表变量接收输出
3. select * from 临时表或表变量 即可。openrowset('sqloledb','Trusted_Connection=yes','exec test_testsp') 其实也是一样的道理,先将结果保存到一个临时结果集中,然后再select
二,对权限的控制,比如说只给存储过程的权限不给表的权限.可以防止SQL注入之类的安全考虑.
--> 测试数据:tb
IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb
GO
CREATE TABLE tb([id] INT,[name] VARCHAR(1))
INSERT tb
SELECT 1,'a' UNION ALL
SELECT 2,'b' UNION ALL
SELECT 3,'c'
--------------开始查询--------------------------IF OBJECT_ID('sp','P') IS NOT NULL DROP PROC sp
GO
CREATE PROC sp
AS
BEGIN
SET NOCOUNT ON UPDATE tb SET name='q' WHERE id =1
SELECT * FROM tb
DELETE FROM TB WHERE id=2END
go
SELECT *
FROM OPENROWSET('SQLNCLI' , 'Server=.;Trusted_Connection=yes;' , 'exec my_test_db.dbo.sp' )----------------结果----------------------------
/*
id name
1 q
2 b
3 c
*/