“'PK_dbo.TableName'不是有效名称”,其中Access ODBC链接表指向SQL Server

时间:2010-03-29 17:35:54

标签: ms-access sql-server-2008 odbc ms-access-2003

我正在尝试使用ODBC将Access 2003 DB链接到SQL Server 2008数据库中的表。当我尝试链接到已建立主键的表时,我收到以下错误消息。

“'Pk_dbo.Batch_Claims'不是有效名称。确保它不包含无效字符或标点符号,并且不会长。”

Pk_dbo.Batch_Claims是我通过SSMS查看表时看到的关键值。我已经使用Access一段时间了,但对SQL Server和使用ODBC的连接有点新。任何帮助将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:3)

您需要通过在SQL Server Management Studio中打开SQL Server(或Azure)数据库来重命名主键。请参阅此博客文章中的“解决无效的主键名称”部分:Linking Microsoft Access 2010 Tables to a SQL Azure Database

答案 1 :(得分:1)

我已经创建了一个存储过程,为您完成了哪些工作。 首先,我们必须删除所有外键,否则我们不能删除主要键约束。 改变我们循环到键下降并重新创建它们

Create procedure proc_changepk
As

    --first drop all references
    declare @sql nvarchar(max)
    declare cursRef cursor for
        SELECT 
        'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
        '].[' + OBJECT_NAME(parent_object_id) + 
        '] DROP CONSTRAINT [' + name + ']' as ref
        FROM sys.foreign_keys   
    open cursRef
        fetch next from cursRef into @sql
        while @@fetch_status = 0 begin
            exec(@sql)
            fetch next from cursRef into @sql
        end
    close cursRef   
    deallocate cursRef

    --drop and recreate primairy keys
    declare @pktable table (constraintname nvarchar(255),tablename nvarchar(255),colname nvarchar(255))
    insert into @pktable(constraintname,tablename,colname)
    SELECT CONSTRAINT_NAME,TABLE_NAME,COLUMN_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1

    declare @pkname nvarchar(255),@tablename nvarchar(255),@cols nvarchar(255)

    declare Mycurs cursor for
        --maybe more than one col for primairy key
        SELECT 
        p.constraintname,p.tablename,
        STUFF((SELECT '. ' + colname from @pktable where constraintname=p.constraintname
                FOR XML PATH('')), 1, 1, '') [cols]
        FROM @pktable p
        GROUP BY constraintname,tablename

    open mycurs
        fetch next from mycurs into @pkname,@tablename,@cols
        while @@fetch_status = 0 begin
            --drop key
            set @sql='alter table ' + @tablename + ' drop CONSTRAINT [' + @pkname + ']'
            print @sql
            exec(@sql)
            --create key
            set @sql='alter table ' + @tablename + ' add CONSTRAINT [pk_' + @tablename + '] primary key NONCLUSTERED (' + ltrim(@cols) + ')'
            print @sql
            exec(@sql)

            fetch next from mycurs into @pkname,@tablename,@cols
        end
    close MyCurs    
    deallocate MyCurs

GO