简体   繁体   中英

Pull column fields into another table as new rows

I'm stumbling on this one, hopefully its easy and I'm looking at it wrong.

I'm receiving formatted xls files. Have a C# app that processes the data and does an SQLBulkCopy insert to my table. There are 5 pairs of columns, one is a Url Text description and one a URL itself. These URLs will reference an html or pdf file I will pull later into a second separate table.

Leaving out unrelated fields, I have a table [Base] with fields:

[ID] (identity)
[BaseID]
...a bunch of other related fields, then...
[LinkText1]
[LinkURL1]
[LinkText2]
[LinkURL2]
[LinkText3]
[LinkURL3]
[LinkText4]
[LinkURL4]
[LinkText5]
[LinkURL5]

The storage for the URLs/files will be in a table [Documents] with fields:

[BaseIdentityID] - references the ID field from [Base] table
[DocIndex] - Each Base record can have 1 - 5 of the URLs filled in. This is to know which URL # it is.
[MimeType]
[Url]
[Text]
[Content]
[Processed] - Bit - Will pull the url data at a later time, this flags that.

I'm using an INSTEAD OF trigger on my [Base] table. These records can be updated so we're keeping archived data in the table. The trigger looks at what we're inserting, flags the existing versions as old, and inserts this new Base record as the CurrentVersion.

In this trigger, I'd now like to insert into the [Documents] table a new row based on each of the 5 pairs of URL data, passing in the [Base] ID identity field for the [BaseIdentityID] in the Documents table, and a 1 for [DocIndex] for LinkURL1, 2 for [DocIndex] for LinkURL2, etc...

Having a hard time visualizing how I will do that exactly. Any suggestions? I'm trying to avoid using cursors as I could have a pretty large collection of Base records to insert.

Thanks.

Maybe you can write this kind of query in an AFTER INSERT trigger:

INSERT INTO [InternationalDR].[dbo].[Documents] ([BaseIdentityID], [DocIndex], [Url], [Text])
SELECT INSERTED.[ID], 1, INSERTED.[LinkURL1], INSERTED.[LinkText1] FROM INSERTED
UNION ALL SELECT INSERTED.[ID], 2, INSERTED.[LinkURL2], INSERTED.[LinkText2] FROM INSERTED
UNION ALL SELECT INSERTED.[ID], 3, INSERTED.[LinkURL3], INSERTED.[LinkText3] FROM INSERTED
UNION ALL SELECT INSERTED.[ID], 4, INSERTED.[LinkURL4], INSERTED.[LinkText4] FROM INSERTED
UNION ALL SELECT INSERTED.[ID], 5, INSERTED.[LinkURL5], INSERTED.[LinkText5] FROM INSERTED;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM