您好我需要知道如何从不同的数据库和不同的服务器中删除记录。
情形:
我有3台服务器,每台服务器包含10个数据库。来自3台服务器的数据库结构完全相同。
示例:我需要从用户表中删除用户名。 3台服务器有用户表,我需要删除的用户名存在于3台服务器中(在用户表中是特定的)。
此外,我需要有一个条件或类似的东西来检查或验证该服务器上此数据库中是否存在该用户。
我所知道的是使用databasename.schema.tablename从不同数据库中删除行。我的问题是当我需要做的脚本需要从不同的服务器跳转时,我该怎么做呢。
有什么建议吗?或者如果你们有不同/更好的想法,那就太好了。
提前致谢!
答案 0 :(得分:2)
假设您有三台服务器server1
,server2
和server3
。它们都在同一个本地网络中,彼此可见。并且假设您有一个域窗口帐户,您现在可以在该帐户下登录,并且此帐户在每个服务器上都有登录。
然后:
-- suppose you decided to delete users from table [user_table],
-- located in databases (which are identical) called [user_database]
-- on server1, server2 and server3 from server1.
USE master; --> server1
GO
EXEC sp_addlinkedserver N'server2', N'SQL Server';
GO
EXEC sp_addlinkedserver N'server3', N'SQL Server';
GO
-- after executing this statements server2 and server3 are linked to server1 -
-- this means that now you can execute queries against server2 and server3 from server1
-- it becomes possible because (as we supposed earlier) you have the domain windows
-- account and linked servers by default is created with a security settings configured
-- in a way that connections through them will be made under the current login's security
-- context - therefore you should be able to get access to the desired servers
-- (in SSMS from server1 check Object Explorer->server1->Server Objects->Linked Servers -
-- you should see server2 and server3 now)
-- ok, now you should be ready to execute DELETE statements against server1 (locally)
-- , server2 and server3 (through linked servers)
USE [user_database]; --> database on server1
GO
delete from user_table where username = 'user_name_you_want_to_delete';
delete from server2.[user_database].dbo.user_table
where username = 'user_name_you_want_to_delete';
delete from server3.[user_database].dbo.user_table
where username = 'user_name_you_want_to_delete';