patternsqlMinor
Inserting two rows from single row
Viewed 0 times
rowstwosingleinsertingfromrow
Problem
I have to import users from the
Here's how I'm doing it currently: http://sqlfiddle.com/#!6/c9b2e/1 (for some reason, it's not outputting anything, but the code works in SSMS).
Is there a way to do this without using two different selects? Maybe self-joining
usersToImport table into the userContact table. usersToImport contains telephone and e-mail information in a single row for each user, but userContact stores one kind of contact information per row.Here's how I'm doing it currently: http://sqlfiddle.com/#!6/c9b2e/1 (for some reason, it's not outputting anything, but the code works in SSMS).
Is there a way to do this without using two different selects? Maybe self-joining
usersToImport or using case somehow.Solution
As Aaron mentioned, for some reason you need to terminate each statement in Fiddle.
Anyway, for the query, you can use
Anyway, for the query, you can use
CROSS APPLY to expand the result set. This method scans the base table only once, and for each row applies the subquery, which in this case actually selects two rows:INSERT INTO userContact(userId, contactType, contactInfo)
SELECT
ui.userId,
c.contactType,
c.contactInfo
FROM usersToImport ui
CROSS APPLY
(
SELECT 'email' AS contactType, ui.email AS contactInfo UNION ALL
SELECT 'telephone', ui.telephone
) c;Code Snippets
INSERT INTO userContact(userId, contactType, contactInfo)
SELECT
ui.userId,
c.contactType,
c.contactInfo
FROM usersToImport ui
CROSS APPLY
(
SELECT 'email' AS contactType, ui.email AS contactInfo UNION ALL
SELECT 'telephone', ui.telephone
) c;Context
StackExchange Database Administrators Q#51337, answer score: 6
Revisions (0)
No revisions yet.