简体   繁体   English

如何使用C#仅从SQL Server 2008 R2备份表数据

[英]How to backup only table data from SQL Server 2008 R2 using C#

I developed a good application with backup and restore feature. 我开发了具有备份和还原功能的良好应用程序。 It works fine. 工作正常。 every time I added new features to its SQL Server 2008 R2 database, for example add a new stored procedure or user-defined table type to upgrade my software. 每次我向SQL Server 2008 R2数据库添加新功能时,例如添加新的存储过程或用户定义的表类型来升级软件。

My backup function is this: 我的备份功能是这样的:

protected int BackUpDataBase(string dbName, string address)
{
    try
    {
        using (_con)
        {
            string command = "Backup database " + dbName + " to disk='" + address + "'";
            SqlCommand cmd = new SqlCommand(command, _con);
            cmd.CommandType = CommandType.Text;
            connect();
            cmd.ExecuteNonQuery();
            return 1;
        }
    }
    catch (SqlException ex)
    {
        return ex.Number * (-1);
    }
}

and my restore function is here: 我的还原功能在这里:

protected int RecoverDataBase(string dbName, string address)
{
    try
    {
        SqlConnection temp = new SqlConnection(_addressMaster);
        string Restore = "USE master" + Environment.NewLine;
        if (CheckDatabaseExists(dbName))
        {
            Restore += @"ALTER DATABASE [" + dbName + "]" + Environment.NewLine;
            Restore += @"SET OFFLINE WITH ROLLBACK IMMEDIATE" + Environment.NewLine;
            Restore += @"ALTER DATABASE [" + dbName + "] SET ONLINE" + Environment.NewLine;
        }
        Restore += @"RESTORE DATABASE [" + dbName + "] FROM DISK = N'" + address + @"' WITH FILE = 1,  NOUNLOAD, REPLACE, STATS = 10" + Environment.NewLine;
        Restore += @"ALTER DATABASE [" + dbName + "] SET Single_User WITH Rollback Immediate" + Environment.NewLine;
        Restore += @"ALTER DATABASE [" + dbName + "] SET Multi_User" + Environment.NewLine;
        using (temp)
        {
            using (SqlCommand cmd = new SqlCommand(Restore, temp))
            {
                cmd.CommandText = Restore;
                cmd.CommandType = CommandType.Text;
                temp.Open();
                cmd.ExecuteNonQuery();
                temp.Close();
                return 1;
            }
        }
    }
    catch (SqlException ex)
    {
        return ex.Number * (-1);
    }
}

Everything is ok BUT! 一切都很好,但是! The problem is here: I developed my upgraded Windows App with new stored procedures and etc, then install it to a new computer and wants to restore the old backup to my upgraded app, all new stored procedures and feature will back to Old because I restored entire old backup not only its data. 问题在这里:我用新的存储过程等开发了升级的Windows App,然后将其安装到新计算机上,并想将旧的备份还原到我的升级的应用程序中,所有新的存储过程和功能都将恢复为旧,因为我已还原整个旧备份不仅包含其数据。 So how can I restore only tables data from a backup file using C# and SQL query? 那么,如何使用C#和SQL查询从备份文件中仅还原表数据?

You cannot restore just the data, but you can script all your objects-modules (you can do it in some mouse click using SSMS) before you restore your backup and then drop all the modules and launch the script that re-creates all the modules. 您不仅可以还原数据,还可以在还原备份然后放下所有模块并启动重新创建所有模块的脚本之前,对所有对象模块(使用SSMS只需单击鼠标即可完成脚本)编写脚本。

Update: 更新:

if you cannot use SSMS, you can script your modules using 如果无法使用SSMS,则可以使用以下命令编写模块脚本

select definition from sys.sql_modules

as CREATE statements. 作为CREATE语句。 The only caveat here is your objects must not be ever renamed because the definition in sys.sql_modules is not updated when you rename a module. 唯一的警告是您的对象绝对不能重命名,因为重命名模块时sys.sql_modules中的定义不会更新。

Other options are: 其他选项是:

  • script the database with the data as INSERT statements (for small data sizes) 使用数据作为INSERT语句对数据库进行脚本编写(适用于小数据量)
  • or import/export data using bcp utility . 或使用bcp实用程序导入/导出数据。 This does not script any object so you should truncate your tables before importing data or recreate the tables if their structure is different from what your backup contains 这不会编写任何对象的脚本,因此,如果导入表的结构与备份所包含的结构不同,则应在导入数据之前截断表或重新创建表

Restore to another environment 还原到另一个环境

Restore your database on another database (a copy or an existing dev/test environment). 在另一个数据库(副本或现有的开发/测试环境)上还原数据库。

RESTORE statement RESTORE陈述式

Then pick only the required data and copy them to the production environment. 然后仅选择所需的数据并将其复制到生产环境。

The way to pick the data and insert them back will entirely depend on what data has to be transfered, and if there are any constraints to add them (indexes, keys, etc...) 挑选数据并将其重新插入的方式完全取决于要传输的数据,以及是否有添加约束(索引,键等)。

Restore Stored Procedures 恢复存储过程

For example here you can get all the STORED PROCEDURE names to drop them. 例如,在这里您可以获取所有存储过程名称以将其删除。

SELECT 'DROP PROCEDURE ' + objects.name FROM sys.sql_modules
INNER JOIN sys.objects
ON objects.object_id = sql_modules.object_id
WHERE objects.type_desc = 'SQL_STORED_PROCEDURE'

Then you can recover create scripts with the following query 然后,您可以使用以下查询恢复创建脚本

SELECT sql_modules.definition FROM sys.sql_modules
INNER JOIN sys.objects
ON objects.object_id = sql_modules.object_id
WHERE objects.type_desc = 'SQL_STORED_PROCEDURE'

DROP Procedure DROP程序

Just put those in an EXEC and make sure it is executed on the Production Database and data is selected from the Copy Database. 只需将它们放在EXEC ,并确保它在生产数据库中执行,并且从复制数据库中选择了数据。

Restore data (without indexes and keys) 恢复数据(无索引和键)

DROP TABLE [prodDB].[mySchema].[myTable]
SELECT * INTO [prodDB].[mySchema].[myTable] FROM [copyDB].[mySchema].[myTable]

Also you can get table definitions from sys.objects table again. 您也可以再次从sys.objects表中获取表定义。

SELECT schemas.name + '.' + objects.name FROM sys.objects
INNER JOIN sys.schemas
ON objects.schema_id = schemas.schema_id
WHERE type_desc = 'USER_TABLE'

Restore data (with indexes and keys) 恢复数据(带有索引和键)

TRUNCATE TABLE [prodDB].[mySchema].[myTable]
INSERT INTO [prodDB].[mySchema].[myTable] SELECT * FROM [copyDB].[mySchema].[myTable]

Also consider reading this post if you have any foreign keys referencing the restored tables : https://stackoverflow.com/a/253858/3635715 如果您有任何外键引用已还原的表,也可以考虑阅读此文章: https : //stackoverflow.com/a/253858/3635715

If you need to get keys definitions you can get them from [sys].[key_constraints] 如果需要获取键定义,可以从[sys].[key_constraints]获取它们[sys].[key_constraints]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用C#以编程方式获取SQL Server 2008 Express R2的默认备份路径? - How can I obtain the default backup path for SQL Server 2008 Express R2 programmatically using C#? 使用C#安装SQL Server 2008 R2 Express - Install SQL Server 2008 R2 Express using C# SQL Server 2008 R2数据库备份和还原功能,通过C#Windows应用程序 - Sql Server 2008 R2 Database backup and restore functionality by C# Windows Application 如何使用C#在SQL Server 2008 R2中拆分和存储XML? - How to split and store XML in SQL Server 2008 R2 using C#? 如何使用C#创建新的SQL Server 2008 R2登录 - How to create new SQL Server 2008 R2 login using C# 如何通过网络从C#ClickOnce应用程序访问SQL Server 2008 R2 - How to access sql server 2008 R2 from C# ClickOnce application over a network 如何在C#中将图像从SQL Server 2008 R2检索到Datagridview [Windows应用程序] - How to retrieve image from SQL Server 2008 R2 to Datagridview in C# [Windows Application] 如何将数据从datagridview保存到SQL Server 2008 R2 - How to save data from datagridview to SQL Server 2008 R2 具有现有SQL Server 2008 R2数据库的C#应用 - C# App with Existing SQL Server 2008 R2 Database 进行设置以使用C#连接到SQL Server 2008 R2中的服务器 - Make a setting to connect to server in SQL Server 2008 R2 using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM