BCP Double-quotes text qualifier output - sql-server-2008

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 "

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)

Multiple IF EXISTS statement

I have a stored procedure that sends daily report for 2 operational machines. I also show on report misfire count per machine but if 1 machine has 0 misfires and the other has more than 0 the Misfire report section will be skipped and not reported.
First I want to check and see if any items exist for specific day and if not send report saying "No results found" or whatever, if they do exist then check to see if any misfires exist on both machines. I want to attach only the stats from the machine that has more than 0 and skip misfire report altogether if they both have 0. I will show what a report looks like that shows Daily Stats that has misfires on both machines.
If say TILT_1 reports 0 misfires and say TILT_2 reports 20 misfires on DAILY SORTER STATS portion then both TILT_1 and TILT_2 MISFIRE REPORT are not attached to report at all. In this instance I would only want to attach TILT_2 MISFIRE REPORT. I hope I am explaining correctly.
Here is the book of a script. Thanks for your help.
DECLARE
#Now DATETIME ,
#Monday DATETIME ,
#Friday DATETIME ,
#StartTime VARCHAR(16) ,
#EndTime VARCHAR(16) ,
#Message VARCHAR (50),
#FileName VARCHAR (50),
#Final VARCHAR (50)
SET #StartTime = '12:01:00AM'
SET #EndTime = '11:59:59PM'
SET #Now = GETDATE()
SET #Monday = DATEADD(dd, DATEDIFF(dd, 0, #Now), -0)
SET #Friday = DATEADD(dd, DATEDIFF(dd, 0, #Now), -0)
SET #Message = 'No results found for'
SET #FileName = CONVERT(varchar(30), GETDATE(), 107) + ' Sorter Stats 17P'
SET #Final = CAST(#message as varchar(70)) + ' ' + CAST(DATENAME (WEEKDAY, #Now)AS VARCHAR (30)) + ',' + ' ' + CONVERT(VARCHAR(30), #Now, 107)
-----------------------------------------------------------------
-----------------------------------------------------------------
IF EXISTS(
SELECT *
FROM [dbo].[StatData]
WHERE CreationTime BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID IN ('TILT_1', 'TILT_2')
HAVING FLOOR(SUM(Throws)/2) = 0
)
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'My_profile',
#recipients = 'whatever#yep.com' ,
#subject = #FileName,
#importance = 'High',
#body = #Final,
#query_result_separator = ' ';
RETURN
END
-----------------------------------------------------------------
-----------------------------------------------------------------
ELSE
IF EXISTS (
SELECT 1
FROM [dbo].[MisfireLog]
WHERE RecordedPeriod BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND WorkstationID IN ('T01', 'T02')
HAVING COUNT (MisfireOrder) = 0
)
BEGIN
--------------------START SORTER STATS.NO MISFIRE INFO-----------
-- Email Query--
DECLARE #Body varchar(max)
declare #TableHead varchar(max)
declare #TableTail varchar(max)
declare #mailitem_id as int
declare #statusMsg as varchar(max)
declare #Error as varchar(max)
declare #Note as varchar(max)
Set NoCount On;
set #mailitem_id = null
set #statusMsg = null
set #Error = null
set #Note = null
Set #TableTail = '</table></body></html>';
--HTML layout--
Set #TableHead =
'<html><head>' +
'<H1 style="color: #000000">Daily Sorter Stats</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Sorter</b></td>' +
'<td align=center><b>Items</b></td>' +
'<td align=center><b>Misfire</b></td></tr>';
--Select information for the Report--
Select #Body= (Select
[TD] = t1.Sorter,
[TD] = t1.Items,
[TD] = t2.Misfire
FROM
(
SELECT Items = floor(sum(Throws)/2)
,Sorter = 'TILT_1'
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1'
)t1
CROSS JOIN
(
SELECT Misfire = isnull(FLOOR(sum(misfire)),0)
,'TILT_1' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1'
)t2
CROSS JOIN
(
SELECT DisabledTrays = isnull(COUNT(SorterID),0)
,'TILT_1' AS Sorter
FROM [dbo].[DisabledCarriers]
WHERE SorterID = 'TILT_1'
)t3
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body = Replace(#Body, '_x0020_', space(1))
Set #Body = Replace(#Body, '_x003D_', '=')
Set #Body = Replace(#Body, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body = Replace(#Body, '<TRRow>0</TRRow>', '')
Set #Body = #TableHead + #Body + #TableTail
-- return output--
Select #Body
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body1 varchar(max)
declare #TableHead1 varchar(max)
declare #TableTail1 varchar(max)
declare #mailitem_id1 as int
declare #statusMsg1 as varchar(max)
declare #Error1 as varchar(max)
declare #Note1 as varchar(max)
Set NoCount On;
set #mailitem_id1 = null
set #statusMsg1 = null
set #Error1 = null
set #Note1 = null
Set #TableTail1 = '</table></body></html>';
--HTML layout--
Set #TableHead1 =
'<html><head>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Sorter</b></td>' +
'<td align=center><b>Items</b></td>' +
'<td align=center><b>Misfire</b></td></tr>';
--Select information for the Report--
Select #Body1= (Select
[TD] = t1.Sorter,
[TD] = t1.Items,
[TD] = t2.Misfire
FROM
(
SELECT Items = isnull(floor(sum(Throws)/2),0)
,'TILT_2' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_2'
)t1
CROSS JOIN
(
SELECT Misfire = isnull(FLOOR(sum(misfire)),0)
, 'TILT_2' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_2'
)t2
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body1 = Replace(#Body1, '_x0020_', space(1))
Set #Body1 = Replace(#Body1, '_x003D_', '=')
Set #Body1 = Replace(#Body1, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body1 = Replace(#Body1, '<TRRow>0</TRRow>', '')
Set #Body1 = #TableHead1 + #Body1 + #TableTail1
-- return output--
Select #Body1
-----------------------------------------------------------------
-----------------------------------------------------------------
--Email
DECLARE #BodyAll varchar(max)
SET #BodyAll = #Body + #Body1
EXEC msdb.dbo.sp_send_dbmail
#profile_name ='My_profile',
#recipients = 'whatever#yep.com',
#subject = #FileName,
#body = #BodyAll,
#body_format = 'HTML'
RETURN
END
ELSE
BEGIN
-----------------------------------------------------------------
-----------------------------------------------------------------
--------------------------------------ALL STATS.WITH MISFIRES----
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body2 varchar(max)
declare #TableHead2 varchar(max)
declare #TableTail2 varchar(max)
declare #mailitem_id2 as int
declare #statusMsg2 as varchar(max)
declare #Error2 as varchar(max)
declare #Note2 as varchar(max)
Set NoCount On;
set #mailitem_id2 = null
set #statusMsg2 = null
set #Error2 = null
set #Note2 = null
Set #TableTail2 = '</table></body></html>';
--HTML layout--
Set #TableHead2 =
'<html><head>' +
'<H1 style="color: #000000">Daily Sorter Stats</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Sorter</b></td>' +
'<td align=center><b>Items</b></td>' +
'<td align=center><b>Misfire</b></td></tr>';
--Select information for the Report--
Select #Body2= (Select
[TD] = t1.Sorter,
[TD] = t1.Items,
[TD] = t2.Misfire
FROM
(
SELECT Items = floor(sum(Throws)/2)
,Sorter = 'TILT_1'
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1'
)t1
CROSS JOIN
(
SELECT Misfire = isnull(FLOOR(sum(misfire)),0)
,'TILT_1' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1'
)t2
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body2 = Replace(#Body2, '_x0020_', space(1))
Set #Body2 = Replace(#Body2, '_x003D_', '=')
Set #Body2 = Replace(#Body2, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body2 = Replace(#Body2, '<TRRow>0</TRRow>', '')
Set #Body2 = #TableHead2 + #Body2 + #TableTail2
-- return output--
Select #Body2
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body3 varchar(max)
declare #TableHead3 varchar(max)
declare #TableTail3 varchar(max)
declare #mailitem_id3 as int
declare #statusMsg3 as varchar(max)
declare #Error3 as varchar(max)
declare #Note3 as varchar(max)
Set NoCount On;
set #mailitem_id3 = null
set #statusMsg3 = null
set #Error3= null
set #Note3 = null
Set #TableTail3 = '</table></body></html>';
--HTML layout--
Set #TableHead3 =
'<html><head>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Sorter</b></td>' +
'<td align=center><b>Items</b></td>' +
'<td align=center><b>Misfire</b></td></tr>';
--Select information for the Report--
Select #Body3= (Select
[TD] = t1.Sorter,
[TD] = t1.Items,
[TD] = t2.Misfire
FROM
(
SELECT Items = isnull(floor(sum(Throws)/2),0)
,'TILT_2' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_2'
)t1
CROSS JOIN
(
SELECT Misfire = isnull(FLOOR(sum(misfire)),0)
, 'TILT_2' AS Sorter
FROM [dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_2'
)t2
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body3 = Replace(#Body3, '_x0020_', space(1))
Set #Body3 = Replace(#Body3, '_x003D_', '=')
Set #Body3 = Replace(#Body3, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body3 = Replace(#Body3, '<TRRow>0</TRRow>', '')
Set #Body3 = #TableHead3 + #Body3 + #TableTail3
-- return output--
Select #Body3
-------------------------------------INSERT MISFIRE STATS HERE---
-- Email Query--
DECLARE #Body4 varchar(max)
declare #TableHead4 varchar(max)
declare #TableTail4 varchar(max)
declare #mailitem_id4 as int
declare #statusMsg4 as varchar(max)
declare #Error4 as varchar(max)
declare #Note4 as varchar(max)
Set NoCount On;
set #mailitem_id4 = null
set #statusMsg4 = null
set #Error4 = null
set #Note4 = null
Set #TableTail4 = '</table></body></html>';
--HTML layout--
Set #TableHead4 = '<html><head>' +
'<H1 style="color: #000000">Tilt 1 Misfire Report</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Misfire Count</b></td>' +
'<td align=center><b>Chute ID</b></td></tr>';
--Select information for the Report--
Select #Body4= (Select
[TD] = isnull(COUNT (MisfireOrder),0),
[TD] = ChuteID
from [dbo].[MisfireLog]
where RecordedPeriod BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND WorkstationID = 'T01'
group by ChuteID
order by COUNT (MisfireOrder) desc
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body4 = Replace(#Body4, '_x0020_', space(1))
Set #Body4 = Replace(#Body4, '_x003D_', '=')
Set #Body4 = Replace(#Body4, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body4 = Replace(#Body4, '<TRRow>0</TRRow>', '')
Set #Body4 = #TableHead4 + #Body4 + #TableTail4
-- return output--
Select #Body4
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body5 varchar(max)
declare #TableHead5 varchar(max)
declare #TableTail5 varchar(max)
declare #mailitem_id5 as int
declare #statusMsg5 as varchar(max)
declare #Error5 as varchar(max)
declare #Note5 as varchar(max)
Set NoCount On;
set #mailitem_id5 = null
set #statusMsg5 = null
set #Error5 = null
set #Note5 = null
Set #TableTail5 = '</table></body></html>';
--HTML layout--
Set #TableHead5 = '<html><head>' +
--'<H1 style="color: #000000">Tilt 2 Misfire Report</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Misfire Count</b></td>' +
'<td align=center><b>Carrier ID</b></td></tr>';
--Select information for the Report--
Select #Body5= (Select
[TD] = isnull(COUNT (MisfireOrder),0),
[TD] = CarrierID
from [dbo].[MisfireLog]
where RecordedPeriod BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND WorkstationID = 'T01'
group by CarrierID
order by COUNT (MisfireOrder) desc
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body5 = Replace(#Body5, '_x0020_', space(1))
Set #Body5 = Replace(#Body5, '_x003D_', '=')
Set #Body5 = Replace(#Body5, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body5 = Replace(#Body5, '<TRRow>0</TRRow>', '')
Set #Body5 = #TableHead5 + #Body5 + #TableTail5
-- return output--
Select #Body5
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body6 varchar(max)
declare #TableHead6 varchar(max)
declare #TableTail6 varchar(max)
declare #mailitem_id6 as int
declare #statusMsg6 as varchar(max)
declare #Error6 as varchar(max)
declare #Note6 as varchar(max)
Set NoCount On;
set #mailitem_id6 = null
set #statusMsg6 = null
set #Error6 = null
set #Note6 = null
Set #TableTail6 = '</table></body></html>';
--HTML layout--
Set #TableHead6= '<html><head>' +
'<H1 style="color: #000000">Tilt 2 Misfire Report</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Misfire Count</b></td>' +
'<td align=center><b>Chute ID</b></td></tr>';
--Select information for the Report--
Select #Body6= (Select
[TD] = isnull(COUNT (MisfireOrder),0),
[TD] = ChuteID
from [dbo].[MisfireLog]
where RecordedPeriod BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND WorkstationID = 'T02'
group by ChuteID
order by COUNT (MisfireOrder) desc
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body6 = Replace(#Body6, '_x0020_', space(1))
Set #Body6 = Replace(#Body6, '_x003D_', '=')
Set #Body6 = Replace(#Body6, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body6 = Replace(#Body6, '<TRRow>0</TRRow>', '')
Set #Body6 = #TableHead6 + #Body6 + #TableTail6
-- return output--
Select #Body6
-----------------------------------------------------------------
-----------------------------------------------------------------
-- Email Query--
DECLARE #Body7 varchar(max)
declare #TableHead7 varchar(max)
declare #TableTail7 varchar(max)
declare #mailitem_id7 as int
declare #statusMsg7 as varchar(max)
declare #Error7 as varchar(max)
declare #Note7 as varchar(max)
Set NoCount On;
set #mailitem_id7 = null
set #statusMsg7 = null
set #Error7 = null
set #Note7 = null
Set #TableTail7 = '</table></body></html>';
--HTML layout--
Set #TableHead7 = '<html><head>' +
--'<H1 style="color: #000000">Tilt 2 Misfire Report</H1>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#F6AC5D>'+
'<td align=center><b>Misfire Count</b></td>' +
'<td align=center><b>Carrier ID</b></td></tr>';
--Select information for the Report--
Select #Body7= (Select
[TD] = isnull(COUNT (MisfireOrder),0),
[TD] = CarrierID
from [dbo].[MisfireLog]
where RecordedPeriod BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND WorkstationID = 'T02'
group by CarrierID
order by COUNT (MisfireOrder) desc
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set #Body7 = Replace(#Body7, '_x0020_', space(1))
Set #Body7 = Replace(#Body7, '_x003D_', '=')
Set #Body7 = Replace(#Body7, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set #Body7 = Replace(#Body7, '<TRRow>0</TRRow>', '')
Set #Body7 = #TableHead7 + #Body7 + #TableTail7
-- return output--
Select #Body7
-----------------------------------------------------------------
-----------------------------------------------------------------
--Email
DECLARE #BodyAll1 varchar(max)
SET #BodyAll1 = #Body2 + #Body3 + #Body4 + #Body5 + #Body6 + #Body7
EXEC msdb.dbo.sp_send_dbmail
#profile_name ='My_profile',
#recipients = 'whatever#yep.com',
#subject = #FileName,
#body = #BodyAll1,
#body_format = 'HTML'
END;
It looks like #Body4 + #Body5 are TILT1, and #Body6 + #Body7 are TILT2
You eventually combine these with:
DECLARE #BodyAll1 varchar(max)
SET #BodyAll1 = #Body2 + #Body3 + #Body4 + #Body5 + #Body6 + #Body7
It also looks like this is what gets the misfire count:
SELECT Misfire = isnull(FLOOR(sum(misfire)),0)
, 'TILT_1' AS Sorter --or `TILT_2`
FROM [PASTEUR].[WSS].[dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1' --or `TILT_2`
If that all is true, you should be able to simply wrap each TILT section in an IF() BEGIN.. END:
IF (SELECT ISNULL(FLOOR,SUM(MISFIRE)),0)
FROM [PASTEUR].[WSS].[dbo].[StatData]
WHERE HourBlock BETWEEN #Monday + ' ' + #StartTime
AND #Friday + ' ' + #EndTime
AND SorterID = 'TILT_1') > 0
BEGIN
--All of #Body4 and #Body5 code
END
Then remove your current IF EXISTS()
You could also handle this when you set #BodyAll1, but this way you don't run all of that extra code to create the TILT tables unless you plan to use those tables.

Insert into a table where column values are passed as comma delimeted values

I have the following script where i want to insert into a table where column name can be passed as comma delimited values. Please suggest different approaches to achieve the following output.
Declare #col_by_source varchar(250) = 's1,s2,s3',
#column_by_target varchar(250) = 'c1,c2,c3',
#SQLString nvarchar(max)
Set #SQLString = 'INSERT INTO [dbo].[sourceTable] (
['+#col_by_source+'] )'
set #SQLString = #SQLString+' '+'SELECT '
Select #SQLString = #SQLString + QUOTENAME(split.a.value('.', 'VARCHAR(100)')) + ' AS '+#col_by_source+','
FROM (SELECT Cast ('<M>' + Replace(#column_by_target, ',', '</M><M>')+ '</M>' AS XML) AS Data) AS A
CROSS apply data.nodes ('/M') AS Split(a);
Set #SQLString = LEFT(#SQLString, LEN(#SQLString) - 1) + ')'
Set #SQLString = #SQLString + 'FROM tableA_source'
print #SQLString
OUTPUT:
INSERT INTO [dbo].[sourceTable] (
[s1,s2,s3] ) SELECT [c1] AS s1,s2,s3,[c2] AS s1,s2,s3,[c3] AS s1,s2,s3 FROM tableA_source
Expected Output:
INSERT INTO [dbo].[sourceTable] (
[s1,s2,s3] ) SELECT [c1] AS s1, [c2] AS s2,[c3] AS s3
FROM tableA_source
Make it as simple. You won't need an alias while doing insert....select.
try like this,
DECLARE #col_by_source VARCHAR(250) = 's1,s2,s3'
,#column_by_target VARCHAR(250) = 'c1,c2,c3'
,#SQLString NVARCHAR(max)
SET #SQLString = 'INSERT INTO [dbo].[sourceTable] (
' + #col_by_source + ' )'
SET #SQLString = #SQLString + ' ' + 'SELECT '
SELECT #SQLString = #SQLString + QUOTENAME(split.a.value('.', 'VARCHAR(100)')) + ' ,'
FROM (
SELECT Cast('<M>' + Replace(#column_by_target, ',', '</M><M>') + '</M>' AS XML) AS Data
) AS A
CROSS APPLY data.nodes('/M') AS Split(a);
SET #SQLString = LEFT(#SQLString, LEN(#SQLString) - 1) + ''
SET #SQLString = #SQLString + 'FROM tableA_source'
PRINT #SQLString

SQL server Full backup job is skipping databases

I have a monthly job running on my SQL server.
It backups all the online databases to a location "\Backupserver\e$\MonthEndBackups\".
Job runs the USP below like this: exec [usp_dba_BackupDatabases] 3
(http://screencast.com/t/l7IS5TZK)
It runs on the last day of the month.
Our databases were scattered around multiple servers and this job runs on those servers and this used to work.
We consolidated all the database on the same server (same SQL instance) and this job does not seem to backup all the databases. I am not sure why? My job has notification(email) on failure and also writes to a log file.
http://screencast.com/t/8ioTZdqEMg9x
http://screencast.com/t/VI3d4GLBTGoX
But nothing fails, so nothing is on the logs and no email notifications show up.
I know it did not work as I don't see the full backups in the folder.
here is the schedule setup:
http://screencast.com/t/waeGwLSa
What could be going wrong? I don't see any pattern in the databases that are not backing up. There are larger databases that are getting backed up.
Can anyone think of why this could be happening? is there any way to trouble shoot this?
USE [DBA]
GO
/****** Object: StoredProcedure [dbo].[usp_dba_BackupDatabases] Script Date: 10/01/2013 11:10:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_dba_BackupDatabases]
#pBackupType SMALLINT
,#pDatabaseName sysname = NULL
AS
SET NOCOUNT ON
DECLARE #vDatabase sysname, #sql VARCHAR(MAX), #vBackupFileFullPath VARCHAR(MAX)
DECLARE c CURSOR FOR
SELECT name FROM sys.sysdatabases
WHERE name NOT IN('tempdb', 'model')
AND DATABASEPROPERTYEX (name,'STATUS') IN( 'ONLINE')
AND (name = #pDatabaseName OR #pDatabaseName IS NULL)
OPEN c
FETCH NEXT FROM c INTO #vDatabase
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT CONVERT(VARCHAR,GETDATE(),121)
PRINT '|-->' + CONVERT(VARCHAR,GETDATE(),121) +' Backup Start for database ' + #vDatabase
IF #pBackupType = 1
BEGIN
SET #vBackupFileFullPath = '\\Backupserver\d$\' + ##SERVERNAME +'\' + #vDatabase +'_DB_'
+REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(16),GETDATE(),112),'-',''),' ',''),':','') +'.bak'
SET #sql = 'BACKUP DATABASE ' + #vDatabase + ' TO DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH FORMAT, INIT, NAME = N' + CHAR(39) + #vDatabase + ' -Full Database Backup' + CHAR(39) + ', SKIP, NOREWIND, NOUNLOAD, STATS = 5, CHECKSUM'
END
IF #pBackupType = 2
BEGIN
SET #vBackupFileFullPath = '\\Backupserver\d$\' + ##SERVERNAME + '\Differential\' + #vDatabase +'_Diff_'
+REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(16),GETDATE(),121),'-',''),' ',''),':','') +'.bak'
SET #sql = 'BACKUP DATABASE ' + #vDatabase + ' TO DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH DIFFERENTIAL , FORMAT, INIT, NAME = N' + CHAR(39) + #vDatabase
+ ' -Differential Database Backup' + CHAR(39) + ', SKIP, NOREWIND, NOUNLOAD, STATS = 5, CHECKSUM'
END
IF #pBackupType = 3
BEGIN
SET #vBackupFileFullPath = '\\Backupserver\e$\MonthEndBackups\' + ##SERVERNAME +'_'+ #vDatabase +'_db.bak'
SET #sql = 'BACKUP DATABASE ' + #vDatabase + ' TO DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH COPY_ONLY, FORMAT, INIT, NAME = N' + CHAR(39) + #vDatabase + ' -Full Month End Database Backup' + CHAR(39) + ', SKIP, NOREWIND, NOUNLOAD, STATS = 5, CHECKSUM'
END
PRINT ' |'+ #sql
EXEC (#sql )
--VERIFY BACKUP
IF #pBackupType = 1
SET #sql = 'RESTORE VERIFYONLY FROM DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH FILE = 1, NOUNLOAD, NOREWIND'
IF #pBackupType = 2
SET #sql = 'RESTORE VERIFYONLY FROM DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH FILE = 1, NOUNLOAD, NOREWIND'
IF #pBackupType = 3
SET #sql = 'RESTORE VERIFYONLY FROM DISK = N' + CHAR(39) + #vBackupFileFullPath + char(39)
+ ' WITH FILE = 1, NOUNLOAD, NOREWIND'
--PRINT ' |'+ #sql
--EXEC (#sql )
PRINT '|-->' + CONVERT(VARCHAR,GETDATE(),121) +' Backup Complete for database ' + #vDatabase
PRINT ''
FETCH NEXT FROM c INTO #vDatabase
END
CLOSE c
DEALLOCATE c
GO
Try with the following options (fixing the options that are likely breaking your current loop and also break sp_MSforeachdb, as I've documented here and corrected here):
DECLARE c CURSOR LOCAL FAST_FORWARD FOR
-----------------^^^^^^^^^^^^^^^^^^
...
WHILE ##FETCH_STATUS <> -1
---------------------^^^^^
Also, please stop declaring VARCHAR without length.

Dynamic SQL in stored procedure doesn't return result set; when run in SSMS I get results

I have a stored procedure that builds a dynamic sql and executes it. It gives no error messages, but it doesn't not return results. However, when I run the code in the sp manually I get the results I'm looking for. Why would this be? The sp takes one nvarchar(max) parameter, #CLM. ANSI_NULLS, QUOTED_IDENTIFIER and NOCOUNT are ON. In the sp there is one temp table #tmpAffPeople. Its columns are EmpLogin nvarchar(8), Matter nvarchar(15), NameandTitle nvarchar(max), TotalHours decimal(6,2), ClientMatter varchar(max). The text of the sp is as follows:
DECLARE #SQLString AS nvarchar(max)
SET #SQLString = ';WITH Emps (EmpLogin, AttorneyAndTitle)
AS
(SELECT EmpLogin,
CASE WHEN EmpTermDate IS NULL OR EmpTermDate = ' + '''' + '''' + ' THEN LastName + ' + '''' + ', ' + '''' + ' + FirstName + ' + ''''+ ' [' + '''' + ' + Title + ' + '''' + '] ' + '''' +
'ELSE LastName + ' + '''' + ', ' + '''' + ' + FirstName + ' + '''' + ' [' + '''' + ' + Title +' + '''' +'] (inactive) ' + '''' + ' END as FullName
FROM [LitigationHold].[dbo].[Employees]
where JobCode IN (' + '''' + '100' + '''' + ',' + '''' + '300' + '''' + ',' + '''' + '400' + '''' + ',' + '''' + '500' + '''' + ',' + '''' + '700' + '''' + ',' + '''' + '800' + '''' + ',' + '''' + '1801' + '''' + '))
INSERT INTO #tmpAffPeople
SELECT t.[EmpLogin],t.Matter, e.AttorneyAndTitle, SUM([Workhours]) AS TotalHours,
c.ClientName + ' + '''' + '/' + '''' + ' + em.MatterDesc
FROM TimeCard t
INNER JOIN Emps e
ON e.EmpLogin = t.EmpLogin
INNER JOIN EliteMatter em
ON t.Matter = em.MatterName
INNER JOIN EliteClient c
ON c.ClientNum = em.ClientNum
WHERE t.Matter IN (' + #CLM + ')
GROUP BY t.EmpLogin, c.ClientName, em.MatterDesc, t.Matter, e.AttorneyAndTitle
ORDER BY TotalHours'
After this runs, in the sp I execute the #SQLString by calling execute with #SQLString right after it between parentheses. I then drop the table. I've done this kind of thing before and never had a problem. What am I missing? I'm using SQL Server 2008R2.
You need to select the rows out of your #tmpAffPeople table to get a result set from your stored procedure