cursor - Iterate through each of the values in one SQL table to find the associated records in another table -
in sql, need return set of records 1 table based on each value of field in lookup table. have lookup table contains filename field , need iterate through each of filenames , find records in table based on field (filename keyfield in both tables). after identify each set of records, need save each of them csv file locally on computer. tried below cursor , it's not working. can assist?
declare @name varchar(50) -- database name declare @path varchar(256) -- path save file declare @filename varchar(256) -- filename output file declare @filedate varchar(20) -- used file name set @path = 'c:\output\' select @filedate = convert(varchar(20),getdate(),112) declare db_cursor cursor select * dbo.filenamelookup fl join dbo.recordstable rt on fl.filename = rt.filename open db_cursor fetch next db_cursor #temp while @@fetch_status = 0 begin set @filename = @path + @name + '_' + @filedate + '.csv' backup database #temp disk = @filename fetch next db_cursor @name end close db_cursor deallocate db_cursor
if you're using mssql, use bcp or sqlcmd utilities. here previous post on same issue:
https://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file
Comments
Post a Comment