我想执行一个位于链接服务器数据库中的存储过程。目前,我在SSMS中使用了以下内容:
INSERT INTO myTable
EXEC [LINKEDSERVER\LINKED].[Data_Base_Name].[Store].usp_GetInfo 1, 1, NULL, 'H'
这会将位于LINKEDSERVER\LINKED.
中的存储过程的结果数据插入到我的本地数据库中
我想用C#的命令来做这件事,有没有合适的方法呢?
谢谢!
发布于 2019-05-17 14:38:24
您可以从DataContext执行SP:
using (DataContext ctx = DataContext())
{
int result = ctx.SP_ProcedureName("1", "2", "3");
}
但首先,您必须在添加表时将其从数据库中添加到DataContext图中,而不是从“存储过程”文件夹中。
这是更具防御性和整洁的解决方案。但如果您更喜欢使用原始命令行,则至少使用参数化查询,如下例所示:
string sqlText = "SELECT columnName FROM Test_Attachments WHERE Project_Id =@PID1 AND [Directory] = @Directory";
SqlCommand myCommand = new SqlCommand(sqlText, SqlConnection);
myCommand.Parameters.AddWithValue("@PID1", 12);
myCommand.Parameters.AddwithValue("@Directory", "testPath");
这是避免SQL注入到代码中的一种方法。此外,您还可以使用finally块来关闭连接:
finally
{
command.Connection.Close();
}
发布于 2019-05-17 15:24:13
谢谢你们的帮助。奥列格也感谢你的建议。我做的是这样的:
qSQL = "INSERT INTO " + tableName + " EXEC [LINKEDSERVER\\LINKED].[Data_Base_Name]." + spName;
using (SqlConnection _connection = new SqlConnection(connectionString))
{
try
{
command = new SqlCommand();
command.Connection = _connection;
command.Connection.Open();
command.CommandText = _qSQL;
command.CommandTimeout = 300; //Because it takes long
SqlTransaction transaction;
transaction = connection.BeginTransaction();
try
{
command.Transaction = _transaction;
command.ExecuteNonQuery();
transaction.Commit();
Debug.WriteLine("Done");
}
catch (SqlException e)
{
Debug.WriteLine("Exception [{0}:{1}]", e.Number, e.Message);
transaction.Rollback();
}
//close connection
command.Connection.Close();
}
catch (SqlException e)
{
command.Connection.Close();
Debug.WriteLine("exception error number: " + e.Number + ": " + e.Message);
}
}
}
如果你对此有任何改进建议,请让我知道。
https://stackoverflow.com/questions/56188567
复制相似问题