如何向联接服务器表格中插入一行数据?

13

我连接的服务器是SourceServer,它有一个链接到TargetServer的联接服务器。

插入语句应该长什么样子(我需要引用链接服务器、数据库、命名空间、表):

//Connected to [SourceServer]

USE [SourceDatabase]

DECLARE @HelloWorld NVARCHAR(255)

SELECT @HelloWorld = Name From dbo.Names where Id = 1

INSERT INTO [TargetServer].[TestDatabase].dbo.TestTable (Name)   VALUES (@HelloWorld)

这个语句会抛出异常:

Too many prefixes.

更新:以上语法正常工作,问题出在连接到链接服务器的 SQL 用户的密码已过期 :)


你确定你的表名或模式名中没有点号"."吗?如果有,你需要再次使用[]。 - StuartLC
没有语法错误,请检查TargetServer值的数值。 - Romil Kumar Jain
这里的名称在我的真实查询中完全正常,在这里完全是虚假的。我明确构建了一个查询,以便插入语句具有较少可能引起异常的位置。 - BanditoBunny
6个回答

22
INSERT INTO [TargetServer].[TestDatabase].[dbo].TestTable (Name)
SELECT Name From [SourceServer].[SourceDatabase].[dbo].[Names] where Id = 1

1
你不需要重写一个假的SQL查询。你的回答是指[TargetServer].[TestDatabase].[dbo].TestTable是可以接受的吗?为什么我会得到太多前缀的异常? - BanditoBunny
也许这可以帮到你:http://social.msdn.microsoft.com/Forums/en/transactsql/thread/5281a959-3a20-4466-af63-272cac97166a - Control Freak
看着这个视图语句,语法至少应该没问题,嗯。 - BanditoBunny

2

如果您正在使用openquery,以下是如何操作:

INSERT INTO OPENQUERY ([LINKEDSERVERNAME], 'SELECT idjob, salarylocal, salarydollars, calification FROM employee')
SELECT 1, 666, 668, 10

1

如果目标表模式已经存在于目标中,请使用以下代码

INSERT INTO [TargetLinkedServerName].[TestDatabase].[dbo].[TargetTestTable] 
SELECT * From [SourceLinkedServerName].[SourceDatabase].[dbo].[SourceTestTable]

如果目标表模式不存在,请使用以下代码(此代码将在目标中创建与源表相同的新表)

select * into [TargetLinkedServerName].[TestDatabase].[dbo].[TargetTestTable] 
 From [SourceLinkedServerName].[SourceDatabase].[dbo].[SourceTestTable]

1
我知道这篇文章发布已经很久了,但我从未找到答案。Select into 返回此错误。Msg 117,级别15,状态1,第41行 对象名“TargetLinkedServerName.TestDatabase.dbo.TestTable”包含超过最大前缀数。最大值为2。 - TheL0grus

0
select * into [TargetServer].[TestDatabase].[dbo].TestTable
 From [SourceServer].[SourceDatabase].[dbo].[Names]

问题是关于插入的。 - Ozzy
1
这个错误是因为对象名'[TargetServer].[TestDatabase].[dbo].TestTable'包含的前缀数量超过了最大限制,最多只能有两个前缀。使用"Insert into"而不是"select * into"语句不会出错,但会将结果添加到现有表的行中,因此需要根据需要进行截断/删除操作。 - Hilary

0

如果您想在链接服务器上插入数据,则需要存在该表

--step 1 on TargetLinkedServerName: 

create table [TestDatabase].[dbo].[TargetTestTable]

--step 2 on SourceLinkedServerName:

INSERT INTO [TargetLinkedServerName].[TestDatabase].[dbo].[TargetTestTable] 
SELECT * From [SourceDatabase].[dbo].[SourceTestTable]

0
我最近也遇到了同样的问题。 我通过以下方法找到了解决办法,即将搜索结果存储到临时表中,然后只将该临时表插入到链接服务器的表中。
SELECT @HelloWorld = Name 
INTO #TempDBA
From dbo.Names where Id = 1

INSERT INTO [TargetServer].[TestDatabase].dbo.TestTable (Name)
SELECT * FROM #TempDBA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接