8 Ways To Export SQL Results To A Text File

You might also like

Download as pdf
Download as pdf
You are on page 1of 12
imtoreview: svavs 0 export SUL Kesuis 10 lec rte Ltps//www.sqlservercentral.com/articles/Export/147145/ Printed 2017/1007 10:14AM. 8 Ways to Export SQL Results To a Text File By Daniel Calbimonte, 2016/09/30 Introduction ‘Thistle wil shows eight ways to export rows from a T-SQU. quar to att ile. We wil show the following options: Shows ress toa file in SQL Server Management Studio (SSMS) SOLCMD Powershell ImporvExpor Wizard in SSMS. i 2 5 4 5. SSIS Wicaed (almost the sume than he namber 4, bu we are wing SSDT instead of SSMS to create the package) 6c 1 SSRs s acr Requirements Youreeda SQL Serer Insalled wi SSIS and SOL Seu Daa Tal ($SD7) Getting Started ook at each ofthe ways we can export the results of 2 query 1, Show results to file in SSMS Inthe ist option, we wil configure SSMS to display the query results ott ile. Welt lowe sng ued mcr now (funantescurces)sfinptoyse) ‘The result displayed in SQL Server Management Studio ($SMS) isthe fllowing: Ponds |p Measce | [Bares alts Gevalia (Opec! you want ose the ress ina x fil, yu ean do this in SSMS, Gio Tools>Options Wj SaLSeneProier 1) Deke Eine ating Avie code Suppt manages coc Inger poe See c_ Select the option Result to fe: vege 1 ore rmtorevew: svavs 0 export SUL Kesuis 10 fe rite vege core 4 Opn (PSL Sever uy sus ane delayed ert tema ebiecte oie ey tion ey ests b sOkSeve Dac er nig se B soaaasenee kawieninaatrDocamen 50 Seve Ove les (Pyne incu deta erp inns uate competes ‘Create a query and exceute the query. An option o specify he nme and pth wil be displayed. We wil cll he resus ina fle named Results 1p jog SV GTO) ss) se 1. + [ie Arinmr » Doce» 26] [sais 2 Orgince © Newtoser Ee Si feertpnem: | sl SenerManagement Sudo edo E boats 1p Dooce AD mse E Paes Bees Bi toaidiee @ pore m24,)

Export Dat ‘You wll open the SQL Server Import and Export wizard imtoreview: svavs 0 export SUL Kesuts 10 lec rte Welcome to SQL Serverimportand Export Wizard ‘hanes ore pct et mst ot en Hue TEarae eh Sekechas Schatten ch ‘ome ir aie nabsiae ieee a ‘We will expt om SQL Sever oF ile Sees the Mieosol OLE DB Provider a the Data Source OnSPER en torteh cr & 7 [Dratoenictommoe Sd eve ot Sores Flt Sarce cae Acie Mises x ORet8 Er) Speci the Server name andthe connection information ifnecessary OnStar noeecsten anc ca & basa LL =) oe fc co ————— am SSS ate Ee ‘In Destination, select Flat File Destination and press browse to specif the file mame and paths veges ore imtoreview: 8vavs export SUL Kesuts 10a ec rie vege sori ‘cafe doch eset tne fo In this example, he lat filename willbe exparizard et: © + tbe Mase + tel a> ] ere Eons meretios [Al name . Dnemedled Type (ip Dowreass ‘Wtecmpnees |) pavenure ons 0M Tabular Model SOL. iT42010345 9H Fleece oer ian aumievonn rene | “he Detop Biter wraanteaaiem Feta | Bidoawmens fe] Now tldr ‘uioamss oman Bowmen |] ere niente Bie Base ee Brave is Bao Bicinaey || Be aieonet nooner) | mame symievems — Teibeure | lf Fz : Fiemme [epotmend One| | Gores) ‘Once that you hae the ile name and path, press next caneten [Prareonmen SSCS Sole earn le omer nef Fieome. Eapesanerene Br] teete: egies) a A | Format femesO™~—OCOCi a Pos ie eee fl Select the option "Write a query to specify the da to transfer" Himtoreview: svays 0 export SUL Kesuis 10 ec rie vege vorie Spocity Tobie Cony or ory & ‘rh aoe Specify the query ofthe fle myquery sq (used nother methods and press parse o verify hat the query is OK. A message spoiling that the statements valid should be displayed Peeper Sa Naor lace a fone sauce tte & Saeaaee FRET OF: Rares awracturee fermen ceeaoee! F500 Wns ras) own ‘Keep the defi values: ‘Conigue Flt Fie Destin § — | Sey act it fe ering tin (a Cie << ss en Select Run immediately to export the da immesitely imtoreview: svavs 0 export SUL Kesuis 10 ec re — | ee aT “The ile created wil esi to this one: BusinesSEntitylD Netione]Dtaber, Orgertzatonlode,OrganizationLevel 23245797967,38,4 4inn2ss7e91, 5006 3 5, SSIS in SSDT ‘You can also use IS in SSDT. This method is similar to he InporvExport Wizard in SSMS, because SSMS calls SSIS to import and export Data, Goto SSDF ad then go to File-New Project a selet Integration Services Project 1 Recent NET Faenet 452 —~| Sets = “ise |G encmemeece! meen ose seices recon Serces St senee In Solution Explorer, right lick SSIS Packages and select S818 Import and Export Wizard com os apse Fl Seaton negate Seis Poet oe 1B integration Serene reject 19 Proecconams B comeion anne nt “The next tes are the same tan in SSMS when we cll the ImportExportwizan, but atthe end, you do nt have the option o run immediately vege sore Hrmtoreview: svays 0 export SUL Kesuis 10 lec rie To run the package, press Start eae sore We owe Green Bl De =: a oeeport “The package will generate a ext ile with the CSV format 60H ‘You ca expat from SQI. Server to atext file using CH, You could als perform a sini ask using Visual Basic Tn his example, we wi use the Script ask ncuded in SSDT Thsepon seyret fyute wigs youreed iets ask ot ete. “Todo this, SSDI, drag and drop the Sent Task: Sm Double lick Script Task and press the Edit ripe button cue ue a a Tor elon (ST tcp wing Vin a 2 Ye 205, = 2 Set ee ——— eon Seiptlngaige Specter ie roronning nguge wey tesco In region Namespaces ad Syxtem.10 and Data SqlClient, Sys. 10 i wed to write information to file (nti scenario ax fle) and Dts SelClient is wed to scomeato SQL Serve Inthe Serp inthe region where is says ald your ede Bete, ad the following code se], (Organtzationtodn), [Organiza ontavel] PROM (HonanReass imtoreview: svavs 0 export SUL Kesuis 10 lec rte vege yori ‘he fs lines wo specify the TSQL Query 1 impteyeel The second line it specify the comecton information (SQL Sever name, database name and Automaton method) ‘The third Tne sto spi the tex file path We will use the SQL Connection an the query an open the connection: ‘Bet eaten Te ith wae ety tek Cy le Wien wl ech el es Header "SussnesoEntstyi0"), resder["Wstionaii0Wunbe:"], reader(*organizetiontode"), reader ["Organizationtevel"]}) + "Catch is used to catch the exception eros. This is used to handle ers. MessageBox Show will show the ror and Ds TaskResult wil show a flue red ear it fal, This code i used wher an exception evor is genetate by the package nally, we will hose the file and SQL Server connection with Reader Close and mile Close 7. Reporting Services Another option it crete a Rept in SQ. Server Reporting Services and save itas CSV. Reporting erviees allows ou to save reports in PDF, Face, XML, METTML, ‘Ward, CSV, Powe:Point and TIFF format I the presentation s important, Reporting Services isthe best option In SSDI, go to File>New Project and select Repor: Server Project Wizard imtoreview: svavs 0 export SUL Kesuts 10a lec rie Reet ‘mmo 53 Sot hy Oda oy Bil Foonsenenon nae sercet [A Welcome wizad wil be displayed, Click next | Welcome to the Report Wizard ‘Thapar input» por ith thc iced you ca 4 | Chonzicypee paneer Specie bneinue one reget Sect atematngtorerson [Con shmop on fuenes tage vege wore Specify the eanncton the SQL Server snd Datahase nti example, we are connecting tothe local SQL. Server andthe AdventreWorks2016CTPS database ‘Select the DataSource SLi aces aR RETEST, = : © Newt oe —— [Littetes hes etsnzce Specify the query: rmtoreview: svays export SuL Kesuis 10a ec rie vege 11 ore Design the Query ect ssuey tenets gathering (ee Ser coy ang SELECT — TOP) Benen NapllNobe, Giger, Ogee 4 Frou "Vonatcnuestnpeyeesoc0 Selec the Tabula Report Type Sclettene strep jouer ce Solect the Report Type Bi @ tate HALAL Hila Huu Hilal Design the tale, press Finish Design the Table ‘lesz howto Geup eed nthe abl Seinen Dreinetontel =a rai Press Preview and in the Save icon, sleet CSV (comma delimited) 10 save the file with the esvexcesion Hrmtorevew: svavs 0 export SUL Kesuis 10 fac rte voce tear Report1 eel Business National Organization rg) Powe EntiyID IDNumber Node or 2 25707967 ti sie! 5 sovsarira sted aren i fewhepert ance ‘CP isthe Bulk Copy Program tat comes with SQL Server Itis used to import data fom a datafile to SQL Server or fiom SQL Server oa data fle Iisa very ast, ‘option Use iif you have millions of rows and you née to use he comand ine rif i ess tcl the command ie from your program Seip “The following example ues bsp to export he quer ress toa ile named bps, Tse to spe that we ate using a Trusted Connection (Windows Connection) an ci ured to perform an operation of dala pe Conclusions ‘There are many ater ways to export resus, However, these options will spite you to ue other ones “Toresume, here you have some ips bout when to we them 1. SSMS destination ole option ~ Taste eset ar sed ed need tao tgs oui ea ce mel. 2, SOLCMD - eri wenyoutn ate ecru wing conmanins sams sees 3. PowerShell - eit wbenyouaeasonatng inks wih Roel er wbenyouae ge ec Foner or 4. Imporixport Wizard in SSMS - Uses whe yout ries rus ea Ses eS oie pein icxting tipi a lige ees 5. $SIS Wizard (almost the same than the number 4, ut we ae using SSDI instead of SSMS to cteate the package), kisindario dh ican cuaieszandyoucn see ‘aly eps ser teated wh eb even ent, roel eden Use Kyte sone saint utes ean een ie oe 6.C#- User wienyoutane cole certs antyusesto mete ithe fede C8 7.SSRS - S828 suet tscreateancecatzedtr Ue habe preening BCP nina ayo he a ao Referens + SSIS Senpt Task 1 Reporing Services Trials + PowerShell Soluions = Several ne or dally sks (Copyright © 2002-2017 Redgate All Righs Reserved Privacy Policy. Tens of Use, Report Abuse

You might also like