我们假设我的表格如下:
id | name | country
--------------------
| John | USA
| Mary | USA
| Mike | USA
有人可以帮我一个可以为所有名字添加id的脚本吗?
由于
答案 0 :(得分:1)
-- Create a temporary table for the example.
CREATE TABLE #People(Id int, Name nvarchar(10), Country nvarchar(10))
-- Insert data, leaving the Id column NULL.
INSERT INTO #People(Name, Country) SELECT
'John', 'USA' UNION ALL SELECT
'Mary', 'USA' UNION ALL SELECT
'Mike', 'USA';
-- 1. Use Row_Number() to generate an Id.
-- 2. Wrap the query in a common table expression (CTE), which is like an inline view.
-- 3. If the CTE references a single table, we can update the CTE to affect the underlying table.
WITH PeopleCte AS (
SELECT
Id,
Row_Number() OVER (ORDER BY (SELECT NULL)) AS NewId
FROM
#People
)
UPDATE PeopleCte SET Id = NewId
SELECT * FROM #People
DROP TABLE #People
答案 1 :(得分:0)
试试这个
update table set a.id=b.newid from table a,(select row_number() over (order by (select null)) newid,name from #temp) b
根据需要进行更改