For the sake of this question context, @Guoxiong answer to cast the columns does work. However, in the grand scheme of things, this answer will be problematic when we want to reimport back to SQL, specifically because we have to deal with the header which without RN will be randomly placed in the generated file, and with RN it will be consider as an extra row...although To skip the first header row in import operation, you can specify the -F 2
option.
SELECT [Style Code], [MY Code] FROM (SELECT 'Style Code' AS [Style Code], 'MY Code' AS [MY Code], 0 AS RN UNION SELECT CAST([Style Code] AS varchar(20)), CAST([MY Code] AS varchar(20)), 1 AS RN FROM [dbo].[UnPivoted_Table]) AS t ORDER BY RN
Therefore, @Erland Sommarskog approach/recommendation is more feasible to the requirements I have, as the goal is to export from a SQL view then reimport into an equivalent SQL table.
The better solution therefore using bcp is as follows:
Referencing MS Docs, follow the following steps:
- Create a format file of the table you plan to import into (or from the source table/view...either is fine as long as they are identical, e.g. same columns, same data types, etc.)
bcp DBName.dbo.ViewOrTableName format null -f "\\...\FormatFileName.fmt" -n -T -S "sqldbserver.domain.com"
If your column names contain spaces, you MUST replace them with underscore in the format file based on answer here by steve smith, otherwise you'll run into this error:
SQLState = 22001, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]String data, right truncation
- Generate a bcp file to export the data from source table/view using the format file created in step1
bcp DBName.dbo.ViewOrTableName out "\\...\fileName.bcp" -f "\\...\FormatFileName.fmt" -T -S "sqldbserver.domain.com"
- Import data into new table using bcp file generated in step2
bcp DBName.dbo.TableName IN "\\...\fileName.bcp" -T -S "sqldbserver.domain.com" -n
Note: -T
is for Integrated Security, so use -U
and -P
options to specify username/password respectively if needed instead.
Note2: When bulk copying to SQL Server, specify the TABLOCK bulk copy hint and set a large batch size to improve performance; you can use -h "TABLOCK"
and -b
switches. Ref