IT박스

SQL Server Management Studio에서 "실제"CSV 형식으로 내보내기 출력을 얻는 방법은 무엇입니까?

itboxs 2020. 11. 14. 10:01
반응형

SQL Server Management Studio에서 "실제"CSV 형식으로 내보내기 출력을 얻는 방법은 무엇입니까?


SQL Server Management Studio에서 실행중인 쿼리가 있습니다 (SQL Server 2005 데이터베이스에 연결). 데이터를 CSV 형식으로 내보내고 싶습니다. 각 열 사이에 쉼표를 붙이는 CSV 형식이 아니라 문자열을 따옴표로 묶는 "실제"CSV 형식입니다. 이렇게하면 쉼표 나 따옴표가있는 데이터를 내보낼 수 있습니다.

내가 보는 모든 예는 워너비 형식으로 제한됩니다. 문자열을 인용하는 옵션이 어디에 있는지 알 수 없습니다.

SSMS가이 기본적인 기능을 진정으로 수행 할 수 없다면 쉽게 수행 할 수있는 다른 도구가 있습니까? 데이터 덤프가 필요할 때마다 C # 프로그램을 작성하고 싶지 않습니다.


SSMS 2012에는 도구-> 옵션-> 쿼리 결과-> SQL Server-> 그리드에 대한 결과에 ".csv 결과를 저장할 때 목록 구분 기호를 포함하는 인용 문자열"이라는 옵션이 있습니다. 그러한 옵션이 얼마나 오랫동안 존재했는지는 모르겠지만 두 가지에 당황합니다.

  1. 기본적으로 켜져 있지 않은 이유
  2. CSV 내보내기 코드의 본질적인 부분이 아닌 옵션 인 이유

제대로 가져올 수없는 CSV 내보내기가 기본 동작이라는 믿음을 무시할뿐입니다. Excel도 똑같이 작동한다는 것을 알아 챘습니다. 옵션이 있는지 확인해야합니다.

그동안 CSV 익스포터가 완전히 쓸모 없다고 외 쳤을 때이 기괴한 기능을 알려준 동료 덕분에 이것이 제가 찾은 최고의 링크 였기 때문에 제가 넣을 것이라고 생각했습니다. 미래의 검색 자들을 위해 여기에있는 지식.

최신 정보

아래 스크린 샷 :여기에 이미지 설명 입력


내 일반적인 해결 방법은 쿼리에 빌드하는 것입니다.

SELECT '"' + REPLACE(CAST(column AS NVARCHAR(4000)), '"', '""') + '"' AS Header, ... FROM ...

이를 사용자 정의 함수로 빌드하여 좀 더 쉽게 만들 수 있지만 각 데이터 유형에 대해 별도의 함수를 빌드해야합니다.


이러한 설정의 다른 조합은 결과가 부정확하거나 부분적인 데이터를 가져올 수 있습니다. 이는 Microsoft가 이러한 문제를 해결하는 것이 중요하다고 생각하지 않았기 때문입니다. 결과를 파일로 보낼 때 CSV 파일에서 어떤 일이 발생하는지 설명하고 있습니다.

좋은 결과를 얻으려면 다음을 수행하십시오.

새 쿼리 창 열기 (새 탭 / 세션) ... 그렇지 않으면 아래 구성이 손실되고 기본값으로 다시 설정됩니다.

따옴표 안의 따옴표를 처리하는 쿼리를 작성하고 모든 문자열 데이터 유형을 따옴표로 묶습니다. 또한 다른 DBMS 및 프로그래밍 언어 문법은 이스케이프 된 큰 따옴표에 대해 다른 구문을 허용합니다 (이 출력을 다른 시스템에 대한 입력으로 사용하는 경우). 일부 사용 \". 일부 사용 "". XML은 ". 아마도 마이크로 소프트가이 기능을 무시하기로 선택한 이유 일 것입니다. 그래서 그들은 논쟁을 다룰 필요가 없었습니다.

.. 새 시스템의 이스케이프 시퀀스가 "".

SELECT '"' + REPLACE(CAST(column1 AS VARCHAR(MAX)), '"', '""') + '"' FROM table1

.. 새 시스템의 이스케이프 시퀀스가 \".

SELECT '"' + REPLACE(CAST(column1 AS VARCHAR(MAX)), '"', '\"') + '"' FROM table1

구성 :

쿼리 옵션> 결과> "결과를 복사하거나 저장할 때 열 머리글 포함"선택

쿼리 옵션> 결과> ".csv 결과를 저장할 때 목록 구분 기호가 포함 된 인용 문자열" -BROKEN; 사용하지 마세요!

쿼리 옵션> 결과> 기타 선택 취소

쿼리 옵션> 결과> 텍스트> 쉼표로 구분 (오른쪽 상단에 설정)

쿼리 옵션> 결과> 텍스트> "결과 집합에 열 머리글 포함"선택

쿼리 옵션> 결과> 텍스트> 기타 선택 취소

쿼리 옵션> 결과> 텍스트> "각 열에 표시되는 최대 문자 수"-문자열이 잘리지 않도록 최대 길이로 설정합니다.

Query> Results To File (3 가지 옵션 모두 전환)

쿼리 실행 (F5)

보고서의 파일 이름에 대한 프롬프트

결과를 보려면 파일을 엽니 다.

NOTE: If you need to do this on a regular basis, you're better off just developing a program that will do this for you in .NET or Java, or whatever language you are comfortable with. Otherwise you have a high probability of making a mistake. Then be extremely aware of the syntax of the system you're importing into, before you define your export out of SQL Server.


How do you feel about Export to CSV from SSMS via PowerShell? This post describes how to define an external tool in SSMS that sends the currently selected query to a PowerShell script which exports to a CSV.


It's sad the option is available in a confusing state, yet not perfectly operational. The following is working at least.

  1. Choose "Tasks>Export Data" from the DB context menu (does not work at Table level either)
  2. For Source, choose "Microsoft OLE DB Provider for SQL Server"
  3. For destination choose "Flat File...", and specify "Format" as delimited and text qualifier as double-quote
  4. Select Table or query (I worked with query)
  5. Finish the wizard

you should be good to go!


I know of no way to do this with SSMS alone. I know TOAD (http://www.toadworld.com/) has a CSV option. Not sure if it is an escaped format. If SSIS is an option, you can convert to a format that escapes strings (true CSV), but that is not in SSMS.

If you have to write a C# program, I would consider querying the table and then running the query, as the metadata will clue which need the escape.


Usually I use this kind of function:

CREATE FUNCTION [dbo].[toExport]
(
    @txt varchar(max)

)
RETURNS varchar(max)
AS
BEGIN

    return REPLACE(REPLACE(REPLACE(@txt, ';', ','), CHAR(10), ' '), CHAR(13), ' ');

END

And in select I put it here:

SELECT dbo.toExport( column_name ) AS column_name FROM ....

And in SMSS 2012 simply Right click on a grid and save results as, or copy all grid (ctrl-A) and ctrl-V to Excel.

It's easiest way to manage data in for example MS Excel without problems with columns.

Of course you must click "Quote strings containing list separators when saving .csv results" in Tools -> Options -> Query Results -> Sql Server -> Results to Grid and increase Maximum Characters Retrieved if you need it.


Maybe this won't work for your application, but I usually get around this problem by exporting to a tab-delimited format. Don't overlook this simple solution if it applies for you.


As all the settings mentioned above didn't fix the CSV my SSMS (SQL Server 2014) generated and exporting a tab-separated file didn't make it any better, a colleague and me made a converter script (Ruby) to convert the SSMS CSV into readable CSV. It keeps encoding, separators and linebreaks of the original file and even does an exact-byte-match validation at the end (it creates a file in the SSMS format from the parsed (!) input file and compares both files).

https://gist.github.com/gr8bit/62202ea89a7e3aff67df2ff080ee8e88

Contact me on github if you encounter errors, please. Cheers!


SSMS 내보내기를 사용하는 대신 Excel을 열고 SQL 연결에서 데이터를 가져 오는 것이 가장 쉬운 방법이라고 생각합니다. SSMS 2016을 사용하고 있으며 ".csv 결과를 저장할 때 목록 구분 기호를 포함하는 인용 문자열"옵션이 없습니다. 아마 작동하지 않기 때문에

Ron

참고 URL : https://stackoverflow.com/questions/6115054/how-to-get-export-output-in-real-csv-format-in-sql-server-management-studio

반응형