C# 存储过程中的模式
我有一个程序,我想读程序的模式。要检索视图模式,我使用此处显示的查询。和我想得到存储过程模式的方法一样。如何得到它?Plz显示一些语法C# 存储过程中的模式,c#,sql,sql-server-2005,stored-procedures,ado.net,C#,Sql,Sql Server 2005,Stored Procedures,Ado.net,我有一个程序,我想读程序的模式。要检索视图模式,我使用此处显示的查询。和我想得到存储过程模式的方法一样。如何得到它?Plz显示一些语法 public static DataTable SchemaReader(string tableName) { string sql = string.Format("Select * from {0}", tableName); conn.Open(); SqlCommand cmd = new SqlCommand(sql,
public static DataTable SchemaReader(string tableName)
{
string sql = string.Format("Select * from {0}", tableName);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
如果您有任何疑问,请提问。提前谢谢。我没有清楚地了解您的问题,我想这对您是有用的
Select *
from sys.objects
where type='p' and name = (procedure name)
用这个替换查询,它将正常工作您可以获得有关存储过程参数的信息,但如果不执行它,SQL Server无法告诉您存储过程返回的数据集的结构。由于执行存储过程可能会产生副作用,ADO.NET没有提供一种方法来告诉您如果要执行存储过程,结果集会是什么样子。此外,结果集可能会根据执行过程时传递给过程的参数而变化。您可以这样做
public static DataTable SchemaReader(string tableName)
{
string sql = "MySP";//replace this with your store procedure name
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
希望有此帮助我已经创建了各种使用存储过程输出的代码生成器。根据我的经验,如果您使用null(DbNull.Value)作为所有参数的值调用它们,那么大多数选择任何内容的过程都会输出相同的模式。您可以从系统视图中获取参数列表本身,尽管我发现使用信息\u SCHEMA.PARAMETERS很方便 通过在事务中执行过程并始终回滚,即使您不知道过程的作用,也可以安全地执行这些内容
您可能需要一个基本的GUI,并允许用户修改参数,或者使用配置文件或其他方式为特定过程提供参数值。存储的进程可能会根据参数生成具有不同模式的输出,尽管我没有见过很多这样的输出。这是一个不调用SP的答案-如果这样做,可能会无意中影响数据:
SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
这将返回结果集:
is_hidden
column_ordinal
name
is_nullable
system_type_id
system_type_name
max_length
precision
scale
collation_name
user_type_id
user_type_database
user_type_schema
user_type_name
assembly_qualified_type_name
xml_collection_id
xml_collection_database
xml_collection_schema
xml_collection_name
is_xml_document
is_case_sensitive
is_fixed_length_clr_type
source_server
source_database
source_schema
source_table
source_column
is_identity_column
is_part_of_unique_key
is_updateable
is_computed_column
is_sparse_column_set
ordinal_in_order_by_list
order_by_is_descending
order_by_list_length
error_number
error_severity
error_state
error_message
error_type
error_type_desc
如果您发布代码、XML或数据示例,请在文本编辑器中突出显示这些行,并单击编辑器工具栏上的“代码示例”按钮(
{}
),以很好地格式化和语法突出显示它!同样在SQL SErver 2005和更高版本中,只查询sys.procedures
会更容易,因为它已经只关注过程-不再需要指定type='p'
。。如果您发布代码、XML或数据示例,请在文本编辑器中突出显示这些行,然后单击“代码示例”按钮({}
)在编辑器工具栏上很好地格式化和语法突出显示它!谢谢。它真的很有效。非常感谢。但是有一个问题,如果我的过程有任何参数,它将无法返回模式。有没有任何方法或技术来克服这个问题。真的很有帮助。谢谢:)+1另外值得一提的是,这也适用于传入的任意SQL,而不是存储的进程名,而且在处理执行速度不快的SQL时,速度似乎要快得多。