You can generate json for each row to avoid line limit, and manually replace the result line break with comma and add brackets to make it array.
SELECT (
SELECT [column1], [column2]
FOR JSON PATH, without_array_wrapper
)
FROM [dbo].[table_name]
Note that you cannot use *
to select all columns.
You can query column names with:
SELECT column_name FROM information_schema.columns WHERE table_name = [table_name]
If you are running in command line, you should use bcp Utility instead of sqlcmd
.
This is the sample powershell script:
# Fetch columns
$columnsQuery = "SET NOCOUNT on;SELECT column_name FROM information_schema.columns WHERE table_name = N'$tableName'"
$columns = sqlcmd -S $DB_SERVER -d $DB_NAME -U $DB_USERNAME -P $DB_PASSWORD -h -1 -u -y 8000 -Q $columnsQuery
# Separate column names with `,`
$columnsCommaSeparated = ($columns -join ',').replace(' ','') -replace '[a-zA-Z0-9_]+', '[$0]'
# Run bcp command
$query="select (select $columnsCommaSeparated for json path, without_array_wrapper) from [$tableName] $conditionExpression"
bcp """$query""" queryout $outFile -S $DB_SERVER -d $DB_NAME -U $DB_USERNAME -P $DB_PASSWORD -w
# Make json Array
$result = Get-Content $outFile
$jsonWithoutBracket = $result -join ','
$json = "[$jsonWithoutBracket]"
# Write
$Utf8WithBomEncoding = New-Object System.Text.UTF8Encoding $True
[System.IO.File]::WriteAllLines($outFile , $json, $Utf8WithBomEncoding)