开发者

increase Ids in table

I would like to increase all ids in my table by 1000 cause I need to insert there data from other table with excactly the same ids. What is the best way to do th开发者_如何学Cat?


update dbo.table set id = id + 1000
go


The best way to go is to not do that. You have to change all related records as well and if you are using identities it gets even more complicated. If you do anything wrong you will seriousl mess up your data integrity. I would suggest that the data you want to insert is the data that needs to have the values changed and if you need to relate back to the data in another tbale, store the original ID in a new field in the table called something like table2id or database2id. If you can't change the existing table, then you can use a lookup table that has both the old id value and the new one.

Under no circumstances should you attempt something of this nature without taking a backup first.


First as HLGEM it seems to be a bad id (think about your foreign keys on id's you must add 1000 to them to).

Second dbo.table has become sys.tables in Server 2008.

Finally you'll need to find the foreign keys columns with this request :

    SELECT name,OBJECT_NAME(object_id)
    FROM sys.columns
    WHERE name like '%id' or name like 'id%' 
--depends on where is 'id' in your columns names

name : the column name, OBJECT_NAME : the table name

And update the whole thing (with a tricky request that should looks like this one, but i didn't test with the "update" command) :

CREATE TABLE #TablesWithIds (
    columnName varchar(100),
    tableName  varchar(100)
)

Insert into #TablesWithIds
SELECT name as columnName,OBJECT_NAME(object_id) as tableName
FROM sys.columns
WHERE name like '%id%' 

update #TablesWithIds.tableName  set #TablesWithIds.columnName = #TablesWithIds.columnName +1000

drop table #TablesWithIds
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜