Export query as a .txt file

You can use bcp utility:

  • In command line:
    bcp "<your query here>" queryout Contacts.txt -c -T
  • Using T-SQL
    DECLARE  
          @query VARCHAR(2048) = 'SELECT * FROM <tablename>'
        , @outputfile VARCHAR(2048) = '\\SERVER1\SHARE1\FOLDER\QueryOutput.txt'
        , @connectionstring VARCHAR(64) = '-U <username> -P <password> -S ' + @@servername
        , @bcpquery VARCHAR(MAX)
       
    SET @bcpquery = 'bcp "@query" QUERYOUT "@outputfile" -c -t -T @connectionstring'
    SET @bcpquery = REPLACE (@bcpquery, '@query', @query)
    SET @bcpquery = REPLACE (@bcpquery, '@outputfile', @outputfile)
    SET @bcpquery = REPLACE (@bcpquery, '@connectionstring', @connectionstring)
    SET @bcpquery = REPLACE(@bcpquery, CHAR(10), '')          -- Remove line breaks

    EXEC master..xp_cmdshell @bcpquery

Is this useful?