SQL Server to MySQL conversion - mysql

I need help to convert this part of stored procedure from MSSQL to MYSQL, any suggestion is appreciated.
P.s. Sorry for my English
set #PARAMS = '#DATA_INIZIO VARCHAR(20),
#DATA_FINE VARCHAR(20),
#SEDE VARCHAR(10)'
set #CMD = 'WITH DriversRN AS
(
SELECT ROW_NUMBER() OVER(ORDER BY '+ #ORDER_BY_RN +') as ROW_NUM, * FROM digitalpodcontrol
WHERE Date BETWEEN #DATA_INIZIO AND #DATA_FINE AND Depot = #SEDE
)
SELECT * FROM DriversRN
WHERE ROW_NUM BETWEEN ' + CONVERT(VARCHAR(50),#MIN__VALUE) + ' AND ' + CONVERT(VARCHAR(50),#MAX__VALUE) + '
ORDER BY ' + #ORDER_BY + ' ' + #DIRECTION
EXECUTE sp_executesql #CMD, #PARAMS, #DATA_INIZIO, #DATA_FINE, #SEDE

Related

special Characters in DB query is failing

I had created a db named as Suri's _DB and had below query is failing when executed. If the db name is given without single quote the query is executing successfully.
The query is
USE [master];
IF EXISTS (SELECT 1 FROM tempdb..sysobjects WHERE [Id] = OBJECT_ID('tempdb..#tmp_filegroups'))
BEGIN
DROP TABLE #tmp_filegroups
END
CREATE TABLE #tmp_filegroups
(
[DbName] nvarchar(128),
[DbId] int,
[GroupName] nvarchar(128),
[GroupId] int,
[IsFileStream] bit
)
IF EXISTS (SELECT 1 FROM tempdb..sysobjects WHERE [Id] = OBJECT_ID('tempdb..#tmp_dbandlogfiles'))
BEGIN
DROP TABLE #tmp_dbandlogfiles
END
CREATE TABLE #tmp_dbandlogfiles
(
[DbName] nvarchar(128),
[DbId] int,
[GroupId] int,
[Name] nvarchar(128),
[FileName] nvarchar(260),
[Size] float,
[IsReadOnlyMedia] bit,
[IsReadOnly] bit,
[IsOffline] bit,
[IsSparse] bit,
[IsPrimaryFile] bit,
[SpaceUsed] float,
[FileType] int
)
IF EXISTS (SELECT 1 FROM tempdb..sysobjects WHERE [Id] = OBJECT_ID('tempdb..#tmp_fulltextcatalogfiles'))
BEGIN
DROP TABLE #tmp_fulltextcatalogfiles
END
CREATE TABLE #tmp_fulltextcatalogfiles
(
[DbName] nvarchar(128),
[DbId] int,
[Name] nvarchar(128),
[Path] nvarchar(260)
)
DECLARE #DB NVARCHAR(128)
DECLARE #DBID int
DECLARE #CMD NVARCHAR(MAX)
DECLARE Databases CURSOR FAST_FORWARD FOR
SELECT name,dbid FROM master..sysdatabases
WHERE name in (N'Suri''s _DB')
OPEN Databases
FETCH NEXT FROM Databases INTO #DB, #DBID
WHILE (##FETCH_STATUS = 0)
BEGIN
BEGIN TRY
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''' + #DB + ''' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],s.name as [GroupName],s.data_space_id as [GroupId], CAST(case s.type when ''FD'' then 1 else 0 end AS bit) AS [IsFileStream] FROM sys.filegroups as s ORDER by [GroupId] ASC'
INSERT INTO #tmp_filegroups execute(#CMD)
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''' + #DB + ''' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],s.data_space_id as [GroupId],s.name AS [Name],s.physical_name AS [FileName],s.size * CONVERT(float,8) AS [Size],s.is_media_read_only AS [IsReadOnlyMedia],s.is_read_only AS [IsReadOnly],CAST(case s.state when 6 then 1 else 0 end AS bit) AS [IsOffline],s.is_sparse AS [IsSparse],CAST(CASE s.file_id WHEN 1 THEN 1 ELSE 0 END AS bit) AS [IsPrimaryFile],CAST(fileproperty(s.name,''SpaceUsed'') AS float) * CONVERT(float,8) AS [SpaceUsed], Type AS [FileType] FROM sys.database_files as s'
INSERT INTO #tmp_dbandlogfiles execute(#CMD)
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''' + #DB + ''' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],cat.name as [Name],cat.path as [Path] FROM sys.fulltext_catalogs AS cat ORDER by [Name] ASC'
INSERT INTO #tmp_fulltextcatalogfiles execute(#CMD)
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ERRMESS
END CATCH
FETCH NEXT FROM Databases INTO #DB, #DBID
END
CLOSE Databases
DEALLOCATE Databases
select [DbName],[DbId],[GroupName],[GroupId],[IsFileStream] from #tmp_filegroups
DROP TABLE #tmp_filegroups
Why this is failing?
I tried escaping the single quotes
When you build the sql query string, the dbname's single quote is not terminated. Replace any single quotes to 2 single quotes to terminate the character.
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''[' + replace(#DB, '''', '''''') + ']'' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],s.name as [GroupName],s.data_space_id as [GroupId], CAST(case s.type when ''FD'' then 1 else 0 end AS bit) AS [IsFileStream] FROM sys.filegroups as s ORDER by [GroupId] ASC'
INSERT INTO #tmp_filegroups execute(#CMD)
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''[' + replace(#DB, '''', '''''') + ']'' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],s.data_space_id as [GroupId],s.name AS [Name],s.physical_name AS [FileName],s.size * CONVERT(float,8) AS [Size],s.is_media_read_only AS [IsReadOnlyMedia],s.is_read_only AS [IsReadOnly],CAST(case s.state when 6 then 1 else 0 end AS bit) AS [IsOffline],s.is_sparse AS [IsSparse],CAST(CASE s.file_id WHEN 1 THEN 1 ELSE 0 END AS bit) AS [IsPrimaryFile],CAST(fileproperty(s.name,''SpaceUsed'') AS float) * CONVERT(float,8) AS [SpaceUsed], Type AS [FileType] FROM sys.database_files as s'
INSERT INTO #tmp_dbandlogfiles execute(#CMD)
SELECT #CMD = 'use ' + '[' + #DB + ']' + '; select N''[' + replace(#DB, '''', '''''') + ']'' as [DbName],' + CAST(#DBID as varchar(30)) + ' as [DbId],cat.name as [Name],cat.path as [Path] FROM sys.fulltext_catalogs AS cat ORDER by [Name] ASC'
INSERT INTO #tmp_fulltextcatalogfiles execute(#CMD)

Setting variables in temp tables

Can anybody help on a problem I am having. For the software i am using it won't accept temp tables unless the table is created and inserted into just like i tried with this.
Before i put in the create table and insert into just the table it works fine but when i try this it says the table already exists.
Can anybody see what i am doing wrong and can advise, it's the variables in my temp tables that is throwing me off.
declare #bt_id varchar(20) = '110';
declare #ms_id varchar(20) = '2';
declare #sqlstr varchar(max) = '';
if object_id('tempdb..#measure_raw') is not null
drop table #measure_raw
CREATE TABLE #measure_raw(
meas_id INT,
column_name VARCHAR (255),
vlu_txt VARCHAR (255),
batch_id INT,
row_num INT,
)
insert into #measure_raw
set #sqlstr = 'select det.meas_id,col.tbl_nm+''.''+col.logged_nm as column_name, det.vlu_txt, det.batch_id, '
+ 'case when (det.row_num is null) then 1 else det.row_num end as row_num '
+ 'into #measure_raw from detail_t det '
+ 'inner join column_t col on col.col_id=det.col_id inner join measure_t rul on rul.meas_id=det.meas_id '
+ 'where det.batch_id = ' + #bt_id + ' '
if #ms_id <> '0'
set #sqlstr = #sqlstr + 'and det.meas_id = ' + #ms_id + ' '
set #sqlstr = #sqlstr + 'order by '
+ 'det.batch_id, det.meas_id, det.row_num, col.tbl_nm, col.logged_nm'
exec(#sqlstr)

Dynamic SQL issue

I have a dynamic SQL which sits inside a stored procedure, but when I run the stored procedure I am not seeing any results. It is very odd, because when I strip out the SQL from the string, and just run it as an SQL Query I do get back results. I have tried getting the Dynamic SQL to print out so I could see what is going on, but this isn't working either. Therefore, I am at a loss to see what I am doing wrong, and would kindly ask if anyone can see what is wrong. Below is the query:
SELECT #SQL = #SQL + 'Select Production_Site, CSN, Target, Action, Fail '
SELECT #SQL = #SQL + 'From syn_products prod, '
SELECT #SQL = #SQL + '(select Production_Site, CSN, SUM([Target]) AS Target,SUM([Action]) AS Action,SUM([Fail]) AS Fail '
SELECT #SQL = #SQL + ' from '
SELECT #SQL = #SQL + ' ( '
SELECT #SQL = #SQL + ' select Production_Site, value, Period, YEAR, week, CSN '
SELECT #SQL = #SQL + ' from t_Pqe_Grocery '
SELECT #SQL = #SQL + ' unpivot ( '
SELECT #SQL = #SQL + ' value '
SELECT #SQL = #SQL + ' for col in (Grocery_Packaging_And_Coding, Grocery_Measurable, '
SELECT #SQL = #SQL + ' Grocery_Appearance, Grocery_Aroma, '
SELECT #SQL = #SQL + ' Grocery_Flavour, Grocery_Texture)) unp '
SELECT #SQL = #SQL + ' ) src '
SELECT #SQL = #SQL + ' pivot '
SELECT #SQL = #SQL + ' ( '
SELECT #SQL = #SQL + ' count(value) '
SELECT #SQL = #SQL + ' for value in ([Target], [Action], [Fail]) '
SELECT #SQL = #SQL + ' ) piv '
SELECT #SQL = #SQL + ' where Production_Site IN ( ''' + #Site + ''') AND YEAR BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToYear))+ 'AND '+ CONVERT(varchar(50),CONVERT(BIGINT,#FromYear))+ 'AND Period BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToPeriod))+ ' AND '+ CONVERT(varchar(50),CONVERT(BIGINT,#FromPeriod))+ 'AND Week BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToWeek))+ ' AND '+CONVERT(varchar(50),CONVERT(BIGINT,#FromWeek))+ ' GROUP BY Production_Site CSN'
SELECT #SQL = #SQL + ' ) pit'
SELECT #SQL = #SQL + ' WHERE prod.pProductCode = pit.CSN AND prod.pPowerBrand = ''POW'''
EXECUTE(#SQL)
Sometimes formatting your query in a different way can help find any errors with your query. You were missing some spaces in your query string:
declare #sql varchar(max)
declare #Site varchar(10) = 'testSite'
declare #ToYear int = 2010
declare #FromYear int = 2012
declare #ToPeriod int = 45
declare #FromPeriod int = 56
declare #ToWeek int = 10
declare #FromWeek int = 1
SET #SQL =
'Select Production_Site, CSN, Target, Action, Fail
From syn_products prod
inner join
(
select Production_Site, CSN, SUM([Target]) AS Target,SUM([Action]) AS Action,SUM([Fail]) AS Fail
from
(
select Production_Site, value, Period, YEAR, week, CSN
from t_Pqe_Grocery
unpivot
(
value
for col in (Grocery_Packaging_And_Coding,
Grocery_Measurable, Grocery_Appearance,
Grocery_Aroma, Grocery_Flavour, Grocery_Texture)
) unp
) src
pivot
(
count(value)
for value in ([Target], [Action], [Fail])
) piv
where Production_Site IN ( ''' + #Site + ''')
AND YEAR BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToYear))+ ' AND '+ CONVERT(varchar(50),CONVERT(BIGINT,#FromYear))
+ ' AND Period BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToPeriod))+ ' AND '+ CONVERT(varchar(50),CONVERT(BIGINT,#FromPeriod))
+ ' AND Week BETWEEN ' + CONVERT(varchar(50),CONVERT(BIGINT,#ToWeek))+ ' AND '+CONVERT(varchar(50),CONVERT(BIGINT,#FromWeek))
+ ' GROUP BY Production_Site CSN
) pit
on prod.pProductCode = pit.CSN
where prod.pPowerBrand = ''POW'''
select #sql
This is now printing --- See SQL Fiddle with Demo -- I also changed the query to use ANSI join syntax instead of comma separated joins.
These are probably syntax errors:
... CONVERT(BIGINT,#ToYear))+ 'AND '+ ...
^--- no space
... #FromYear))+ 'AND Period BETWEEN ...
^---no space
... #FromPeriod))+ 'AND Week BETWEEN
^-- yet again no space
One of your variables is probably NULL. Concatenating a NULL value into your string will result in a NULL string. Both PRINT and EXECUTE when given NULL strings..
First, you need to set the #SQL parameter to an empty string or change the first line to set the value instead of concatenating it. Then, you may need to do some kind of checking to verify the parameters are NOT NULL and, if they are, either remove the criteria, or substitute something else:
DECLARE #SQL VARCHAR(MAX)
SELECT #SQL = ''
SELECT #SQL = #SQL + ... -- now build the SQL Statement
SELECT #SQL = #SQL + ' where Production_Site IN ( ''' + ISNULL(#Site, '') + ''' ... -- check for NULLs here
PRINT ISNULL(#SQL, 'NULL) -- this should now print something even if the SQL is NULL
Finally, beware of SQL injection attacks! Avoid concatenating parameters into a dynamic SQL statement like this. Instead, parameterize the dynamic SQL, and pass the parameters along with the EXECUTE statement.

Creating 'util' - stored procedure section, as with .net helper classes

A few minutes ago I was only searching for a simple syntax (SQL server) query that will copy a table Row .
This is usually done from time to time, when working on a ASP.net project, testing data with queries
inside the SQL SERVER management studio . so one of the routine actions is copying a row, altering the required columns to be different from each other, then testing data with queries
So I've encountered - this stored procedure- ,as answer by Dan Atkinson
but adding it to where all non testing purpose are stored lead me to think
is it possible to store them in sorted order so I could Distinguish
'utils' or 'testingPurpose' ones from those used in projects
(default folder inside managment treeview is Programmabilty) could this be another folder too
or this is not an option ?
if not , I thought of Utils. prefix like that (if no other way exist)
dbo.Utils.CopyTableRow
dbo.Utils.OtherRoutineActions ....
Or there's a designated way to achieve what I was thinking of.
this is a first "Util" stored procedure i've made , found it's only solution
prefexing it via Util_
ALTER PROCEDURE [dbo].[Utils_TableRowCopy](
#TableName VARCHAR(50) ,
#RowNumberToCopy INT
)
AS
BEGIN
declare #RowIdentity sysname =
(SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName)
)
DECLARE #columns VARCHAR(5000), #query VARCHAR(8000);
SET #query = '' ;
SELECT #columns =
CASE
WHEN #columns IS NULL THEN column_name
ELSE #columns + ',' + column_name
END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (
TABLE_NAME = LTRIM(RTRIM(#TableName))
AND
column_name <> LTRIM(RTRIM(#RowIdentity))
);
SET #query = 'INSERT INTO ' + #TableName + ' (' + #columns + ') SELECT ' + #columns + ' FROM ' + #TableName + ' WHERE ' + #RowIdentity + ' = ' + CAST(#RowNumberToCopy AS VARCHAR);
--SELECT SCOPE_IDENTITY();
declare #query2 VARCHAR(100) = ' Select Top 1 * FROM '+ #TableName +' Order BY ' + #RowIdentity + ' desc' ;
EXEC (#query);
EXEC (#query2);
END

BCP Double-quotes text qualifier output

I have a bcp command that is pushing the results of a query into a flat file that is comma delimited unicode. I need the fields to be encapsulated in double quotes with the text identifier being double quotes.
Here's an example of the csv output:
36029,2,Oct 11 2004 1:01AM,4,23537,0.10
Where it needs to be:
"36029","2","Oct 11 2004 1:01AM","4","23537","0.10"
I suspect it uses the -q flag but I'm not sure how to actually use the -q. The MS documentation is not doing much to help me out.
Sorry if this is a dupe, I looked hard I swear!
try this:
Exec Master..xp_Cmdshell 'bcp "SELECT '"' + col1 + '"', '"' + col2+ '"', '"' + col3+ '"'
FROM table1" queryout "C:\mcg1.csv" -c -t,"'
If you extract from within Eclipse it puts double quotes around text and dates. I do this from the view Data Source Explorer. Right click -> Data -> Extract...
You can also utilize SQL servers QuoteName function to specify the column that should have quotes. This also gives the ability to add any character in place of quotes
Exec Master..xp_Cmdshell 'bcp "SELECT QuoteName(col1,Char(34)),QuoteName(col2,Char(34)),... FROM table1" queryout "C:\test.csv" -c -t,"'
Take a look here to learn more
SQL Server BCP Utility Experts Guide
DECLARE #DBName VARCHAR(100) = 'dbname'
,#TableName VARCHAR(100) = 'example'
,#FileNamePath VARCHAR(100) = 'example.csv'
,#MaxRowsPerFile INT = 999999999
,#Resume BIT = 0
,#PrintVarValues BIT = 1
,#ConvertDates BIT = 1
,#QuotedStrings BIT = 0
,#delimitor VARCHAR(1) = ','
--Generate column names as a recordset
DECLARE #columns VARCHAR(8000)
,#columnsas VARCHAR(8000)
,#columnsformatted VARCHAR(8000)
,#sql VARCHAR(8000)
,#HeaderFile VARCHAR(100)
,#DataFile VARCHAR(100)
,#FileCount INT
,#TotalRows INT
,#RowCount INT
,#IntVariable INT
,#SQLString NVARCHAR(4000)
,#ParmDefinition NVARCHAR(512)
,#FileCountName VARCHAR(100)
,#PrimaryColumn NVARCHAR(128)
,#FileExtension VARCHAR(10)
,#Quote1 VARCHAR(10) = ''
,#Quote2 VARCHAR(10) = '';
IF (#QuotedStrings = 1)
BEGIN
SELECT #Quote1 = 'QUOTENAME('
,#Quote2 = ',CHAR(34))'
END
IF (
len(isnull(#DBName, '')) > 1
AND len(isnull(#TableName, '')) > 1
)
BEGIN
EXEC ('USE [' + #DBName + '];')
SELECT #FileCount = 1
,#RowCount = 1
IF (OBJECT_ID(N'dbo.#CreateExcel') IS NOT NULL)
BEGIN
IF (#Resume = 0)
BEGIN
DROP TABLE dbo.#CreateExcel
END
ELSE
BEGIN
SELECT #FileCount = FileCount
,#RowCount = [RowCount]
FROM dbo.#CreateExcel WITH (NOLOCK)
END
END
IF (OBJECT_ID(N'dbo.#CreateExcel') IS NULL)
BEGIN
CREATE TABLE dbo.#CreateExcel (
FileCount INT
,[RowCount] INT
)
INSERT INTO dbo.#CreateExcel (
FileCount
,[RowCount]
)
VALUES (
1
,1
)
END
SELECT #FileExtension = CASE
WHEN CHARINDEX('.', REVERSE(#FileNamePath)) > 1
THEN RIGHT(#FileNamePath, CHARINDEX('.', REVERSE(#FileNamePath)))
ELSE '.XLS'
END
SELECT #FileNamePath = CASE
WHEN CHARINDEX('.', REVERSE(#FileNamePath)) > 1
THEN LEFT(#FileNamePath, LEN(#FileNamePath) - CHARINDEX('.', REVERSE(#FileNamePath)))
ELSE #FileNamePath
END
SELECT #HeaderFile = substring(#FileNamePath, 1, len(#FileNamePath) - charindex('\', reverse(#FileNamePath))) + '\HeaderFile.xls'
SELECT #DataFile = substring(#FileNamePath, 1, len(#FileNamePath) - charindex('\', reverse(#FileNamePath))) + '\DataFile.xls'
SET #SQLString = N'SELECT #Primary_Column = bb.[name] FROM (' + N'SELECT TOP 1 co.[name] ' + N'FROM [' + #DBName + N'].[sys].[objects] ao with (nolock) ' + N' inner join [' + #DBName + N'].[sys].[columns] co with (nolock) ' + N' on ao.object_id = co.object_id ' + N'WHERE ao.[name] = ''' + #TableName + N'''' + N' AND ((co.is_identity=1) ' + N' or (co.column_id =1 and co.IS_NULLABLE=0) ' + N' or (co.system_type_id=36 /*uniqueidentifier*/) ' + N' or (co.system_type_id in (42,61,189) /*datetimes*/)) ' + N'ORDER BY co.is_identity desc, co.column_id asc, co.system_type_id asc) bb';
SET #ParmDefinition = N'#Primary_Column NVARCHAR(128) OUTPUT';
EXECUTE sp_executesql #SQLString
,#ParmDefinition
,#Primary_Column = #PrimaryColumn OUTPUT;
SET #SQLString = N'SELECT #cols=coalesce(#cols+'','','''')+''[''+co.[name]+'']'', ' + N'#colsas=coalesce(#colsas+'','','''')+''' + #Quote1 + '''''''+co.[name]+''''''' + #Quote2 + ''', ' + N'#colsformatted=coalesce(#colsformatted+'','','''')+CASE WHEN co.[system_type_id] in (98,167,175,231,239,241) THEN
''' + #Quote1 + 'REPLACE(REPLACE([''+co.[name]+''],CHAR(13),CHAR(32)),CHAR(10),CHAR(32))' + #Quote2 + '''
WHEN co.[system_type_id] in (35,99) THEN
''' + #Quote1 + 'REPLACE(REPLACE(CAST([''+co.[name]+''] AS VARCHAR(8000)),CHAR(13),CHAR(32)),CHAR(10),CHAR(32))' + #Quote2 + '''
WHEN ' + LTRIM(RTRIM(CAST(#ConvertDates AS INT))) + N'=1 AND co.[system_type_id] in (40,42,58,61) THEN
''' + #Quote1 + 'CONVERT(varchar(10),[''+co.[name]+''],101)+'''''''' ''''''''+LEFT(RIGHT(CONVERT(varchar(24),[''+co.[name]+''],109),12),8)+'''''''' ''''''''+RIGHT(LTRIM(RTRIM(CONVERT(varchar(24),[''+co.[name]+''],100))),2)' + #Quote2 + '''
ELSE ''[''+co.[name]+'']''
END ' + N'FROM [' + #DBName +
N'].[sys].[objects] ao with (nolock) ' + N' inner join [' + #DBName + N'].[sys].[columns] co with (nolock) ' + N' on ao.object_id = co.object_id ' + N'WHERE ao.[name] = ''' + #TableName + N'''';
SET #ParmDefinition = N'#cols VARCHAR(8000) OUTPUT, #colsas VARCHAR(8000) OUTPUT, #colsformatted VARCHAR(8000) OUTPUT';
EXECUTE sp_executesql #SQLString
,#ParmDefinition
,#cols = #columns OUTPUT
,#colsas = #columnsas OUTPUT
,#colsformatted = #columnsformatted OUTPUT;
--Create HeaderFile.XLS
SET #sql = 'exec master..xp_cmdshell ''bcp "SELECT ' + REPLACE(REPLACE(#columnsas, CHAR(34), CHAR(34) + CHAR(34)), CHAR(39), CHAR(39) + CHAR(39)) + '" queryout "' + #HeaderFile + '" -c -t ' + CASE
WHEN #delimitor IS NULL
THEN ''
ELSE #delimitor
END + ' -T'''
IF (#PrintVarValues = 1)
BEGIN
PRINT #sql
END
EXEC (#sql)
SET #SQLString = N'SELECT #Total_Rows = count(1) from [' + #DBName + N']..[' + #TableName + N'] with (nolock)';
SET #ParmDefinition = N'#Total_Rows INT OUTPUT';
EXECUTE sp_executesql #SQLString
,#ParmDefinition
,#Total_Rows = #TotalRows OUTPUT;
WHILE (#RowCount <= #TotalRows)
BEGIN
--Create incremental filename for each chuck of rows from table in database
IF (#PrintVarValues = 1)
BEGIN
PRINT 'Percent Complete: ' + ltrim(rtrim(cast(cast((#RowCount * 100) / #TotalRows AS INT) AS VARCHAR(10)))) + '%'
END
SET #FileCountName = #FileNamePath + Right(REPLICATE('0', 3) + ltrim(rtrim(CAST(#FileCount AS VARCHAR(4)))), 4) + #FileExtension
--populate data into incremental filename
SET #sql = 'exec master..xp_cmdshell ''bcp "SELECT ' + #columnsformatted + ' FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [' + #PrimaryColumn + '] ASC) AS [ROW_NUMBER], ' + #columns + ' FROM [' + #DBName + ']..[' + #TableName + '] ) foo WHERE [ROW_NUMBER] BETWEEN ' + LTRIM(RTRIM(CAST(#RowCount AS NVARCHAR(10)))) + ' AND ' + LTRIM(RTRIM(CAST(#RowCount - 1 + #MaxRowsPerFile AS NVARCHAR(10)))) + '" queryout "' + #DataFile + '" -c -t ' + CASE
WHEN #delimitor IS NULL
THEN ''
ELSE #delimitor
END + ' -T'''
IF (#PrintVarValues = 1)
BEGIN
PRINT #sql
END
EXEC (#sql)
--Merge headerfile.xls with incremental filename
SET #sql = 'exec master..xp_cmdshell ''copy /b ' + #HeaderFile + '+' + #DataFile + ' ' + #FileCountName + ''''
IF (#PrintVarValues = 1)
BEGIN
PRINT #sql
END
EXEC (#sql)
--update TempCreateExcel table with running values in case needing to abort and restart from checkpoint reached.
SELECT #FileCount = #FileCount + 1
,#RowCount = #RowCount + #MaxRowsPerFile
UPDATE dbo.#CreateExcel
SET FileCount = #FileCount
,[RowCount] = #RowCount
END
IF (#PrintVarValues = 1)
BEGIN
PRINT 'Percent Complete: 100%'
END
DROP TABLE [dbo].#CreateExcel
END
use:
select col1, col2, quotename(col3, '\"') from table1 -- backslash before double quote to escape the "