如何防止此错误
" OLE DB提供程序" MSDASQL"用于链接服务器返回的消息 " [Teradata] [ODBC Teradata驱动程序] [Teradata数据库]对象 ' teradataDB.tablename'不存在。"
我使用openquery来检查teradata表是否存在,如果存在,则删除表并从select中重新创建表。我使用openquery将teradata表中的数据插入到sql server表中。 但是,当我运行存储过程时,它会给我上面的错误,因为它执行插入并首先在最后两行选择。如何修改它以先运行第一个块然后再运行最后两行?
DECLARE @strSql NVARCHAR(MAX) = ''
DECLARE @TableName NVARCHAR(50)
DECLARE @linkedServer NVARCHAR(50)
DECLARE @TabExists BIT
DECLARE TableCursor CURSOR LOCAL FOR
SELECT TABLENAME FROM #TableList
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @strSql='Select count(1) as TabExists FROM DBC.TABLES WHERE TABLEKIND=''T'' AND DATABASENAME=''teradataDB'' AND TABLENAME=''' +@TableName+ ''''
SET @strSql = N'select @TabExists=TabExists from OPENQUERY('+@linkedServer+', ''' + REPLACE(@strSql, '''', '''''') + ''')'
EXEC sp_executesql @strSql, N'@TabExists BIT OUT', @TabExists OUT;
FETCH NEXT FROM TableCursor INTO @TableName
IF (@TableName ='tablename')
BEGIN
IF (@TableName ='tablename') AND (@TabExists = 1)
BEGIN
EXEC sp_executesql
N'
EXEC (
''DROP TABLE teradataDB.tablename'') AT [linkedserver];'
END
EXEC sp_executesql
N'
EXEC (
''CREATE TABLE AS SELECT (
~~~~
)
'' ) AT [linkedserver];'
END
END
CLOSE TableCursor
DEALLOCATE TableCursor
INSERT INTO sqlServerDB.tablename
SELECT * FROM OPENQUERY (linkedserver, 'SELECT columns FROM teradataDB.tablename')
答案 0 :(得分:0)
您可以使用以下代码代替CURSOR
以上的代码。
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
DROP TABLE teradataDB.tablename
END
现在您不需要创建表的结构,并触发以下查询。
INSERT INTO sqlServerDB.tablename
SELECT * FROM OPENQUERY (linkedserver, 'SELECT columns FROM teradataDB.tablename')