I have a table with 100 records with no PK.
I need to add random GUID to it. Before:
First Name Last Name GUID
John Smith
Alex Smith
etc
After:
First Name Last Name GUID
John Smith 34234234gyerfw
Alex Smith werwer32r23r
etc
Currently I can do it by:
Creating an identity column with values, then make a while loop and generate newid(). Any option on how to do this without a loop?
Just add the empty column and then do an UPDATE
.
ALTER TABLE YourTable
ADD GUID UNIQUEIDENTIFIER
UPDATE YourTable
SET GUID = NEWID()
Add the GUID column as NOT NULL
with a default of NEWID()
ALTER TABLE
[dbo].[Text]
ADD [GUID] uniqueidentifier NOT NULL DEFAULT NEWID()
This will automatically populate the existing rows, an you will not need to specify a guid when inserting records.
You can add a column and update the value or create a persisted column that has a default constraint with NEWID()
create table test (id int identity
, column1 uniqueidentifier not null default newid()
, column2 varchar(10))
insert into test(column2)
values ('a')
select * from test
alter table test
add column3 uniqueidentifier
update test
set column3 = NEWID()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.