我想知道是否有办法从SQL Server 2008 R2中获取存储过程代码?
例如,如果我有以下代码来创建此存储过程:
USE AdventureWorks;
GO
CREATE PROCEDURE HumanResources.uspGetEmployeesTest2
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SET NOCOUNT ON;
SELECT FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName
AND EndDate IS NULL;
GO
有没有办法可以编写SQL语句来获取'SET NO COUNT ON' to 'IS NULL'
之间的所有内容?
答案 0 :(得分:1)
非常简单,实际上 - 只需加入sys.procedures
和sys.sql_modules
系统目录视图即可获取存储过程定义。
这个C#代码说明了这种方法:
string connectionString = "server=YourServerName;Database=YourDatabaseName;Integrated Security=SSPI;";
string query = @"SELECT m.definition
FROM sys.procedures pr
INNER JOIN sys.schemas s ON pr.schema_id = s.schema_id
INNER JOIN sys.sql_modules m ON pr.object_id = m.object_id
WHERE pr.Name = @Name AND s.Name = @Schema;";
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 255).Value = "uspGetEmployeesTest2";
cmd.Parameters.Add("@Schema", SqlDbType.VarChar, 255).Value = "HumanResources";
conn.Open();
object returnValue = cmd.ExecuteScalar();
conn.Close();
if (returnValue != null)
{
string procedureDefinition = returnValue.ToString();
}
}
这将返回所有内容 - 从CREATE PROCEDURE
到程序的最后一行
答案 1 :(得分:0)
不确定。一种方法是戳INFORMATION_SCHEMA.ROUTINES
。在查询编辑器中,您可以这样:
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_SCHEMA = 'HumanResources'
AND ROUTINE_NAME = `uspGetEmployeesTest2`
然后,您可以使用WHERE
和LIKE
进一步优化所需的文字。