[英]SQL-server assigning a value to an primary key incremental value
I got two primary keys: 'ID' and 'last modified'. 我有两个主键:“ ID”和“最后修改”。
ID is an identity which is incremental, that is, when I am adding a new row, it will be like: ID是一个增量身份,即当我添加新行时,它将像:
ID | last modified |value1|value2|value3|...|value_n|
-- |---------------------------|------|------|------|---|-------|
1 | 2011-10-01 13:03:00.000 |................................|
2 | 2011-10-01 14:03:00.000 |................................|
Im adding those new rows from different tables, so I would like to update rows up to some conditions, and also, I would like to add new rows which refers to the same ID. 我添加了来自不同表的那些新行,因此我想将行更新到某些条件,并且还要添加引用相同ID的新行。 I will give an example: 我举一个例子:
ID = 1, new row. ID = 1,新行。 ID = 2, new row. ID = 2,新行。
Some conditions lead to insert a new row, which refer to the same ID (ID = 2), changing the last modified datetime too. 某些情况导致插入新行,该行引用相同的ID(ID = 2),同时也更改了上次修改的日期时间。
ID | last modified |value1 |value2|value3|...|value_n|
-- |---------------------------|------ |------|------|---|-------|
1 | 2011-10-01 13:03:00.000 |................................ |
2 | 2011-10-01 14:03:00.000 |old value..|..................... |
2 | 2011-10-01 15:03:00.000 |other value|.........................|
After that some conditions lead to update a row (referring to a particular ID, in this case, ID = 2), it will take the last modified time, and update it, and also update the last modified datetime: 之后,某些条件导致更新行(在此情况下,指的是特定的ID,ID = 2),它将花费最后修改的时间,并对其进行更新,并且还更新最后修改的日期时间:
ID | last modified |value1 |value2|value3|...|value_n|
-- |---------------------------|---------|------|------|---|-------|
1 | 2011-10-01 13:03:00.000 |................................ |
2 | 2011-10-01 14:03:00.000 |................................ |
2 | 2011-10-01 16:03:00.000 |new value|.........................|
However, when I am adding a new row, even though I assign the same ID to the ID column, it is ignoring the assigning and it is increasing the ID, illustating this: 但是,当我添加新行时,即使我向ID列分配了相同的ID,它也忽略了分配,而是在增加ID,说明了这一点:
ID | last modified |value1 |value2|value3|...|value_n|
-- |---------------------------|---------|------|------|---|-------|
1 | 2011-10-01 13:03:00.000 |................................ |
2 | 2011-10-01 14:03:00.000 |................................ |
3 | 2011-10-01 16:03:00.000 |.........|.........................|
I attach the code: 我附上代码:
IF (SELECT COUNT(*) FROM myTable WHERE myColumn = @myValue ) = 0
--change value
BEGIN
INSERT INTO myTable(ID, value1,value2...) VALUES (@ID, value1,value2..)
END
However, and as I said, the assigning (ID = @ID) is not actually assingning because it is a PK is an autoincremental value and PK. 但是,就像我说的那样,分配(ID = @ID)实际上不是分配值,因为它是一个PK,是一个自动递增的值和PK。
How can I make it right?? 我该怎么做? Any Ideas? 有任何想法吗?
您需要将要插入值的表的标识插入设置为打开,然后再插入记录。
SET IDENTITY_INSERT YourTableName ON
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.