Let's assume my table is the following:
id | name | country
--------------------
| John | USA
| Mary | USA
| Mike | USA
Someone can help me with a script that can add id's to all names?
Thanks
Let's assume my table is the following:
id | name | country
--------------------
| John | USA
| Mary | USA
| Mike | USA
Someone can help me with a script that can add id's to all names?
Thanks
-- 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
try this
update table set a.id=b.newid from table a,(select row_number() over (order by (select null)) newid,name from #temp) b
make changes like ordering as needed