【问题标题】:Use procedure of one database and save data into another database table using C#使用一个数据库的过程并使用C#将数据保存到另一个数据库表中
【发布时间】:2020-02-02 10:51:12
【问题描述】:

我有很多数据库,数据库是通过输入连接字符串动态更改的。但是我在一个数据库中有一个程序,假设名为“DB1”,并且想将数据插入另一个名为“DB2”的数据库中。

我无法为插入目的创建另一个连接字符串,因为我不了解数据库。

我的代码:

SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);

conn1.Open();

SqlCommand cmd3 = new SqlCommand();
cmd3.Connection = conn1;
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.CommandText = "storedProcedure";

cmd3.Parameters.AddWithValue("@Col0", string.IsNullOrEmpty(index[0].ToString()) ? (object)DBNull.Value : index[0].ToString());    
cmd3.Parameters.AddWithValue("@Col1", string.IsNullOrEmpty(index[1].ToString()) ? (object)DBNull.Value : index[1].ToString());
cmd3.Parameters.AddWithValue("@Col2", string.IsNullOrEmpty(index[2].ToString()) ? (object)DBNull.Value : index[2].ToString());
cmd3.Parameters.AddWithValue("@Col3", string.IsNullOrEmpty(index[3].ToString()) ? (object)DBNull.Value : index[3].ToString());

cmd3.ExecuteNonQuery();

我正在使用两个连接字符串,一个用于使用过程,第二个用于将数据插入特定数据库。我想将数据插入到名为 connString1 的第二个连接字符串中。但我不知道我该怎么做。

我的连接字符串:

<add name="connString" 
     connectionString="Data Source=DBSERVER-PC\SQL2012;Database=DB1;User ID=sa;Password=a "
     providerName="System.Data.SqlClient" />

<add name="connString1" 
     connectionString="Data Source=DBSERVER-PC\SQL2012;Database=DB2;User ID=sa;Password=a "
     providerName="System.Data.SqlClient" />

知道如何解决这个问题吗?

【问题讨论】:

  • 有什么原因不能将存储过程部署到两个数据库中?
  • 我有存储过程的 Db1,但我想将数据插入另一个数据库。所以我们可以一次使用一个连接字符串,对吧?那我该怎么办?
  • 问题不清楚。存储过程是用于检索数据还是用于插入数据?
  • 存储过程用于插入数据。程序在database1中,想往另一个database2的表中插入数据。
  • 如果数据库在同一个服务器,看看这个link

标签: c# .net sql-server stored-procedures


【解决方案1】:

假设您在(Database) DB1 中有一个名为 FROM dbo.item 的表

--------------------
item_id | base_price
--------------------
   1    |   10.5

   2    |   6.5

你想要这个 table insert into another (Database) DB2[dbo].[Testitem]

CREATE PROCEDURE dbo.Sp_InsertData
(
@DBNAME VARCHAR(100) = NULL     
)
AS
BEGIN

DECLARE @str VARCHAR(MAX)       
SET @str='INSERT INTO ' + @DBNAME + '.dbo.Testitem(item_id, base_price) select item_id, base_price from dbo.item '
exec (@str)

END

执行 SP 的测试脚本

EXEC dbo.Sp_InsertData
@DBNAME='DB2'

注意:- 您已将 Database(DB2) 名称从代码后面传递为 @Paramter in DB1 使用web.config.....

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2017-05-02
    • 2015-12-08
    相关资源
    最近更新 更多