[英]Is it possible to programmatically create a DBLink in SQL server 2005 in C#?
Is it possible to programmatically create a DBLink in SQL server 2005 in C#? 是否可以以C#在SQL Server 2005中以编程方式创建DBLink?
Suppose I have database A and B. I want to create a DBlink in A to connect B. I will capture the B database info from user and create the DBLink in database A. Is this possible in C# .Net version 2.0? 假设我有数据库A和B。我想在A中创建一个DBlink以连接B。我将捕获用户的B数据库信息,并在数据库A中创建DBLink。在C#.Net 2.0版中可以吗?
You can add a linked server with sp_addlinkedserver: 您可以使用sp_addlinkedserver添加链接服务器:
EXEC sp_addlinkedserver
@server = 'OracleHost',
@srvproduct = 'Oracle',
@provider = 'MSDAORA',
@datasrc = 'MyServer'
From C#, you can store this query in a SqlCommand, and call ExecuteNonQuery() to execute it on the database. 从C#,您可以将此查询存储在SqlCommand中,然后调用ExecuteNonQuery()在数据库上执行它。
What you wanna do is make a Stored Procedure that does this and then call it from C# 您想要做的是创建一个存储过程来执行此操作,然后从C#中调用它
Make the following stored procedure: 进行以下存储过程:
Create PROCEDURE [dbo].[LinkMyServer]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
EXEC sp_addlinkedserver @server = N'LinkName',
@srvproduct = N' ',
@provider = N'SQLOLEDB',
@datasrc = N'some.domain.or.ip.com',
@catalog = N'database_name'
EXEC sp_addlinkedsrvlogin N'LinkName', false, N'ServerDomain\Administrator', N'user_on_remotedb', N'password_on_remote_db'
END
Now the remote db has been linked to the Local User Administrator. 现在,远程数据库已链接到本地用户管理员。
Now in C# you just make a SqlCommand and and set type to stored procedure and execute a non query :) 现在,在C#中,您只需执行SqlCommand并将类型设置为存储过程并执行非查询:)
ServerDomain\\Administrator could also just be a sql user like 'dbo'. ServerDomain \\ Administrator也可以只是一个SQL用户,例如“ dbo”。
Hope this helped. 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.