简体   繁体   English

如何提取MS SQL Server表的主键列的名称?

[英]How to pull out the name of the primary key column(s) of a MS SQL Server table?

I have a MS SQL Server Database with about 75 tables on it, and I am trying to insert records into tables if a record with the same primary key doesn't exist, or update if they do. 我有一个包含约75个表的MS SQL Server数据库,如果不存在具有相同主键的记录,则尝试将记录插入表中;如果存在,则尝试更新。 I could hard code the primary keys for every table into my vb.net code, but I'd rather not as more tables are to be added at a later date and my code needs to handle this without being changed. 我可以将每个表的主键硬编码到我的vb.net代码中,但是我不希望以后再添加更多表,并且我的代码需要处理而不更改。 Is there a way to pull out the primary key column name(s) from a table using a query so I can loop through each table executing the same code? 有没有一种方法可以使用查询从表中拉出主键列名,以便我可以遍历执行相同代码的每个表?

Thanks, Tom 谢谢汤姆

PS I am a bit of a newbie when it comes to SQL so if you have the time please be simple and clear with any responses. PS:对于SQL来说,我还是个新手,所以如果您有时间,请给我简单明了的答复。

Have a look at Find Tables With Primary Key Constraint in Database 看看数据库中具有主键约束的查找表

SELECT  i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM    sys.indexes AS i INNER JOIN 
        sys.index_columns AS ic ON  i.OBJECT_ID = ic.OBJECT_ID
                                AND i.index_id = ic.index_id
WHERE   i.is_primary_key = 1

There is a simpler way of doing this. 有一种更简单的方法。 It is called ADO.NET :) 它被称为ADO.NET :)

Basically, you need a DataAdapter to fetch the data from your DB to a DataSet . 基本上,您需要一个DataAdapter才能将数据从数据库中获取到DataSet You then add, modify or remove rows to a DataTable in the DataSet and when you're ready to commit to the DB you tell DataAdapter to do so. 然后,您可以在DataSetDataTable中添加,修改或删除行,并在准备提交给DB时告诉DataAdapter这样做。 The DataSet can keep track of the changes made to it and the DataAdapter knows what statement to use depending on the RowState property of a row/record. DataSet可以跟踪对其所做的更改,并且DataAdapter根据行/记录的RowState属性知道要使用的语句。

See here how to retrieve and modify data using ADO.NET. 请参阅此处如何使用ADO.NET检索和修改数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM