Hi There,
I need your help please.
I need to extract data from many tables. This is a brief run down.
Get all records from table1 and for each record found look for related records in table2 so the data exported will look like.
Table1 Details
Table2 Details
Table2 details
Table1 Details
Table2 Details
Table2 details
Table2 Details
Table2 details
etc
Could someone let me know how I do that.
Thank you.
Best Regards,
Steve.
select * from table1
join table2 on table1.? = table2.?
where ? indicates the column used to find related rows (preferred name over "records")
Are you wanting to export to another table or to a (text) file?
Hi Scott,
Thanks for the reply.
Ultimately it will be exported to a .csv file.
Best Regards,
Steve.
That's actually easier, since you can concatenate everything to a single text value. Once you get the code below validated, you can use that as the base query for an Export from SSMS or for bcp if you want to use only T-SQL. Naturally the "TOP (10)" are just to allow for quick testing.
SELECT concat_columns
FROM (
SELECT TOP (10) 1 AS table_code, t1.key_col, <code_to_concat_all_table1_columns> AS concat_columns
FROM dbo.table1 t1
UNION ALL
SELECT TOP (10) 2 AS table_code, t2.key_col, <code_to_concat_all_table2_columns> AS concat_columns
FROM dbo.table2 t2
) AS derived
ORDER BY table_code, key_col