65.9K
CodeProject 正在变化。 阅读更多。
Home

以编程方式生成 SQL 脚本

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.80/5 (34投票s)

2009年9月8日

CPOL
viewsIcon

271756

如何使用 C#.NET 生成 SQL 对象脚本

引言

本文将向您展示如何使用 C#. NET 轻松生成 SQL Server 数据库对象脚本。

背景

本文对希望生成 SQL Server 数据库对象脚本(如存储过程、视图等)的开发人员有所帮助。

Using the Code

这是一种非常简单的方法……我希望您同意我的观点,即 Microsoft 产品与您的自定义应用程序集成的灵活性非常出色。 Microsoft SQL Server 提供了一个特殊的存储过程 "sp_helptext",该存储过程允许您获取给定对象的描述。

我编写了一个函数,用于从给定的对象获取 SQL 脚本。您只需要提供三个参数

  • 连接字符串
  • 对象名称
  • 对象类型(我使用它来确定是否为表)
语法
exec sp_helptext 'object'

下面给出了一个示例代码。

示例代码

public string GetScript(string strConnectionString
                      , string strObject
                      , int ObjType)
{
    string strScript = null;
    int intCounter = 0;
    if (ObjType != 0)
    {
        ObjSqlConnection = new SqlConnection(strConnectionString.Trim());

        try
        {
            ObjDataSet = new DataSet();
            ObjSqlCommand = new SqlCommand("exec sp_helptext 
				[" + strObject + "]", ObjSqlConnection);
            ObjSqlDataAdapter = new SqlDataAdapter();
            ObjSqlDataAdapter.SelectCommand = ObjSqlCommand;
            ObjSqlDataAdapter.Fill(ObjDataSet);

            foreach (DataRow ObjDataRow in ObjDataSet.Tables[0].Rows)
            {
                strScript += Convert.ToString(ObjDataSet.Tables[0].Rows[intCounter][0]);
                intCounter++;
            }
        }
        catch (Exception ex)
        {
           strScript = ex.Message.ToString();
        }
        finally
        {
            ObjSqlDataAdapter = null;
            ObjSqlCommand = null;
            ObjSqlConnection = null;
        }
    }

    return strScript;
}

关注点

存储过程 sp_helptext 不允许您获取任何表描述。

结论

我希望本文对您有所帮助。祝您愉快!

历史

  • 2009 年 9 月 8 日:初始发布
© . All rights reserved.