执行存储过程后如何分辨数据类型?
时间:2020-03-05 18:44:37 来源:igfitidea点击:
在Management Studio中执行存储过程时,是否有办法使结果集的数据类型返回?我正在寻找类似的功能,当我们将表名称传递给sp_help时
解决方案
回答
如果不分析系统注释以查看其从何处查询的内容,就不会想到简单的方法。如果可以编辑SP以选择XML,则可以将XML_INFO添加到查询中以返回架构。
回答
但是,如果通过ADO,ADO.NET,ODBC或者类似方法调用存储过程,则确实要查看类型:生成的记录集具有我们要查找的类型信息。我们真的仅限于Management Studio吗?
回答
我们可以始终使用被保证具有唯一性的实际表。这是一个冲突,但这是一个选择。但是,这在存储的proc中将不起作用。
if exists (select * from sys.tables where name = 'tmp_TableName') drop table tmp_TableName go select * into tmp_TableName from MyTable --do some stuff go if exists (select * from sys.tables where name = 'tmp_TableName') drop table tmp_TableName go
回答
实际上,我们可以在SP中执行此操作:
EXEC ('if exists (select * from sys.tables where name = ''tmp_TableName'') drop table tmp_TableName') EXEC ('select * into tmp_TableName from MyTable') -- Grab the column types from INFORMATION_SCHEMA here EXEC ('if exists (select * from sys.tables where name = ''tmp_TableName'') drop table tmp_TableName')
虽然,我认为必须有更好的方法。
回答
这不是最优雅的解决方案,但是我们可以使用OPENROWSET将存储的proc结果放入表中,然后使用sp_help对其进行描述。
例如
select * into tmp_Results from openrowset( 'SQLOLEDB.1' , 'Server=your_server_name;Trusted_Connection=yes;' , 'exec your_stored_proc') exec sp_help 'tmp_Results' drop table tmp_Results
回答
最好的选择是将存储过程更改为函数。但这仅在环境允许的情况下有效。