سؤال

So I have a huge script file that will inset loads and loads of data into my database, here is a sample.

INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES (NEWID(), 'Argentina');
INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES (NEWID(), 'Armenia');
INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES (NEWID(), 'Aruba');

No I have 100s if not 1000s of NEWID() tags, however I need to re-use a alot of these ID's. So I want to replace all NEWID() with an actual random GUID. So the output would look like.

INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES ('42FF2BE3-D2A7-4FD1-AAA9-6AA0FDBDDD28', 'Argentina');
INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES ('59FF040C-5102-41D8-9F8B-782B42983F0E', 'Armenia');
INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES ('7589B5F1-21C0-4EF8-897E-B8C7FF8EDFA9', 'Aruba');

I am using Notepad++ to write this, so maybe if you know a Regex I can use in the Find and Replace would be great. Or if you know another way.

Thanks, Ben

هل كانت مفيدة؟

المحلول

NEWID() is actually a random GUID.

If you want to reuse it, e.g. when populating a child table, you can grab it again from the parent table, e.g. let's say you populate a country and then need to populate a state table:

INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES (NEWID(), 'Australia');

INSERT INTO [dbo].[SysState] ([state_id], [country_id], [state_name])
SELECT 
   NEWID(),
   (SELECT [country_id] FROM [dbo].[SysCountry] WHERE [country_name] = 'Australia'),
   'Victoria'

You can also use a local variable to do the same - the script will look better:

INSERT INTO [dbo].[SysCountry] ([country_id], [country_name]) VALUES (NEWID(), 'Australia');

DECLARE @id uniqueidentifier
SELECT @id = [country_id] FROM [dbo].[SysCountry] WHERE [country_name] = 'Australia'
INSERT INTO [dbo].[SysState] ([state_id], [country_id], [state_name])
    VALUES (NEWID(), @id, 'Victoria')
INSERT INTO [dbo].[SysState] ([state_id], [country_id], [state_name])
    VALUES (NEWID(), @id, 'New South Wales')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top