I am using the stored procedure, saveDelimitedColumns (found: http://www.virtualobjectives.com.au/sqlserver/saving_), to save data results as a .csv file. This works great with one exception...when it saves as a .csv file the column headers within excel have brackets. For example, [Client ID], I would like the column heading to be without brackets, as Client ID.
Below is the savedelimitedcolumns stored procedure and I cannot figure out if there is a way to make it so there are no brackets when it publishes as a .csv file.
Is it possible to make an alteration somewhere in the code below to accomplish this?
Thank you,
ALTER PROCEDURE [dbo].[SaveDelimitedColumns]
#PCWrite varchar(1000) = NULL,
#DBFetch varchar(4000),
#DBWhere varchar(2000) = NULL,
#DBThere varchar(2000) = NULL,
#DBUltra bit = 1,
#Delimiter varchar(100) = 'CHAR(44)', -- Default is ,
#TextQuote varchar(100) = 'CHAR(34)', -- Default is " Use SPACE(0) for none.
#Header bit = 0, -- Output header. Default is 0.
#NullQuoted bit = 0,
#DateTimeStyle tinyint = 120 -- CONVERT Date Time Style. Default is ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Return int
DECLARE #Retain int
DECLARE #Status int
SET #Status = 0
DECLARE #TPre varchar(10)
DECLARE #TDo3 tinyint
DECLARE #TDo4 tinyint
SET #TPre = ''
SET #TDo3 = LEN(#TPre)
SET #TDo4 = LEN(#TPre) + 1
DECLARE #DBAE varchar(40)
DECLARE #Task varchar(6000)
DECLARE #Bank varchar(4000)
DECLARE #Cash varchar(2000)
DECLARE #Risk varchar(2000)
DECLARE #Next varchar(8000)
DECLARE #Save varchar(8000)
DECLARE #Work varchar(8000)
DECLARE #Wish varchar(max)
DECLARE #Name varchar(100)
DECLARE #Same varchar(100)
DECLARE #Rank smallint
DECLARE #Kind varchar(20)
DECLARE #Mask bit
DECLARE #Bond bit
DECLARE #Size int
DECLARE #Wide smallint
DECLARE #More smallint
DECLARE #DBAI varchar(2000)
DECLARE #DBAO varchar(8000)
DECLARE #DBAU varchar(max)
DECLARE #Fuse int
DECLARE #File int
DECLARE #HeaderString varchar(8000)
DECLARE #HeaderDone int
SET #DBAE = '##SaveFile' + RIGHT(CONVERT(varchar(10),##SPID+100000),5)
SET #Task = 'IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE name = ' + CHAR(39) + #DBAE + CHAR(39) + ') DROP TABLE ' + #DBAE
EXECUTE (#Task)
SET #Bank = #TPre + #DBFetch
IF NOT EXISTS (SELECT * FROM sysobjects WHERE RTRIM(type) = 'U' AND name = #Bank)
BEGIN
SET #Bank = CASE WHEN LEFT(LTRIM(#DBFetch),6) = 'SELECT' THEN '(' + #DBFetch + ')' ELSE #DBFetch END
SET #Bank = REPLACE(#Bank, CHAR(94),CHAR(39))
SET #Bank = REPLACE(#Bank,CHAR(45)+CHAR(45),CHAR(32))
SET #Bank = REPLACE(#Bank,CHAR(47)+CHAR(42),CHAR(32))
END
IF #DBWhere IS NOT NULL
BEGIN
SET #Cash = REPLACE(#DBWhere,'WHERE' ,CHAR(32))
SET #Cash = REPLACE(#Cash, CHAR(94),CHAR(39))
SET #Cash = REPLACE(#Cash,CHAR(45)+CHAR(45),CHAR(32))
SET #Cash = REPLACE(#Cash,CHAR(47)+CHAR(42),CHAR(32))
END
IF #DBThere IS NOT NULL
BEGIN
SET #Risk = REPLACE(#DBThere,'ORDER BY' ,CHAR(32))
SET #Risk = REPLACE(#Risk, CHAR(94),CHAR(39))
SET #Risk = REPLACE(#Risk,CHAR(45)+CHAR(45),CHAR(32))
SET #Risk = REPLACE(#Risk,CHAR(47)+CHAR(42),CHAR(32))
END
SET #DBAI = ''
SET #DBAO = ''
SET #DBAU = ''
SET #Task = 'SELECT * INTO ' + #DBAE + ' FROM ' + #Bank + ' AS T WHERE 0 = 1'
IF #Status = 0 EXECUTE (#Task) SET #Return = ##ERROR
IF #Status = 0 SET #Status = #Return
-- For all columns (Fields) in the table.
DECLARE Fields CURSOR FAST_FORWARD FOR
SELECT '['+C.name+']', C.colid, T.name, C.isnullable, C.iscomputed, C.length, C.prec, C.scale
FROM tempdb.dbo.sysobjects AS O
JOIN tempdb.dbo.syscolumns AS C
ON O.id = C.id
JOIN tempdb.dbo.systypes AS T
ON C.xusertype = T.xusertype
WHERE O.name = #DBAE
ORDER BY C.colid
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
OPEN Fields
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
FETCH NEXT FROM Fields INTO #Same, #Rank, #Kind, #Mask, #Bond, #Size, #Wide, #More
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
-- Convert to character for header.
SET #HeaderString = ''
DECLARE #sql nvarchar(4000)
DECLARE #cDelimiter nvarchar(9)
DECLARE #cTextQuote nvarchar(9)
DECLARE #TypeFound bit
SET #sql = N'select #cDelimiter = ' + #Delimiter
EXEC sp_executesql #sql, N'#cDelimiter varchar(9) output', #cDelimiter output
SET #sql = N'select #cTextQuote = ' + #TextQuote
EXEC sp_executesql #sql, N'#cTextQuote varchar(9) output', #cTextQuote output
WHILE ##FETCH_STATUS = 0 AND #Status = 0
BEGIN
SET #TypeFound = 0
-- Build header.
IF LEN(#HeaderString) > 0 SET #HeaderString = #HeaderString + #cDelimiter + ISNULL(#cTextQuote + REPLACE(#Same, #cTextQuote, REPLICATE(#cTextQuote, 2))+#cTextQuote, SPACE(0))
IF LEN(#HeaderString) = 0 SET #HeaderString = ISNULL(#cTextQuote + REPLACE(#Same, #cTextQuote, REPLICATE(#cTextQuote, 2))+#cTextQuote, SPACE(0))
IF #Kind IN ('char','nchar','varchar','nvarchar','text','ntext','sysname','xml')
BEGIN
IF #NullQuoted = 0
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+REPLACE(' + #Same + ','+#TextQuote+',REPLICATE('+#TextQuote+',2))+'+#TextQuote+',SPACE(0))'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+REPLACE(' + #Same + ','+#TextQuote+',REPLICATE('+#TextQuote+',2))+'+#TextQuote+',SPACE(0))'
END
IF #NullQuoted = 1
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+REPLACE(' + #Same + ','+#TextQuote+',REPLICATE('+#TextQuote+',2))+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+REPLACE(' + #Same + ','+#TextQuote+',REPLICATE('+#TextQuote+',2))+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
END
SET #TypeFound = 1
END
IF #Kind IN ('bit','tinyint','smallint','int','bigint')
BEGIN
IF #NullQuoted = 0
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL(CONVERT(varchar(128),' + #Same + '),SPACE(0))'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL(CONVERT(varchar(128),' + #Same + '),SPACE(0))'
END
IF #NullQuoted = 1
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL(CONVERT(varchar(128),' + #Same + '),'+#TextQuote+'+'+#TextQuote+')'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL(CONVERT(varchar(128),' + #Same + '),'+#TextQuote+'+'+#TextQuote+')'
END
SET #TypeFound = 1
END
IF #Kind IN ('numeric','decimal','money','smallmoney','float','real')
BEGIN
IF #NullQuoted = 0
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL(CONVERT(varchar(128),' + #Same + '),SPACE(0))'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL(CONVERT(varchar(128),' + #Same + '),SPACE(0))'
END
IF #NullQuoted = 1
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL(CONVERT(varchar(128),' + #Same + '),'+#TextQuote+'+'+#TextQuote+')'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL(CONVERT(varchar(128),' + #Same + '),'+#TextQuote+'+'+#TextQuote+')'
END
SET #TypeFound = 1
END
IF #Kind IN ('uniqueidentifier','geometry','geography')
BEGIN
IF #NullQuoted = 0
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ')+'+#TextQuote+',SPACE(0))'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ')+'+#TextQuote+',SPACE(0))'
END
IF #NullQuoted = 1
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ')+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ')+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
END
SET #TypeFound = 1
END
IF #Kind IN ('datetime2','datetime','smalldatetime','time','date','datetimeoffset')
BEGIN
IF #NullQuoted = 0
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ','+convert(varchar(3),#DateTimeStyle)+')+'+#TextQuote+',SPACE(0))'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ','+convert(varchar(3),#DateTimeStyle)+')+'+#TextQuote+',SPACE(0))'
END
IF #NullQuoted = 1
BEGIN
IF #Rank = 1 SET #DBAU = ' ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ','+convert(varchar(3),#DateTimeStyle)+')+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
IF #Rank > 1 SET #DBAU = #DBAU + '+' + #Delimiter + '+ISNULL('+#TextQuote+'+CONVERT(varchar(128),' + #Same + ','+convert(varchar(3),#DateTimeStyle)+')+'+#TextQuote+','+#TextQuote+'+'+#TextQuote+')'
END
SET #TypeFound = 1
END
IF #TypeFound = 0
BEGIN
SET #Retain = 'ERROR: Data type ' + UPPER(#Kind) + ' was used but not supported by SaveDelimitedColumns.'
SET #Status = #Retain
END
FETCH NEXT FROM Fields INTO #Same, #Rank, #Kind, #Mask, #Bond, #Size, #Wide, #More
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
END
CLOSE Fields DEALLOCATE Fields
IF LEN(#DBAU) = 0 SET #DBAU = '*'
IF #PCWrite IS NOT NULL AND (#DBUltra = 0) AND (#Header = 1)
BEGIN
SET #HeaderString = replace(#HeaderString, '"', '""')
SET #DBAI = ' SELECT ' + CHAR(39) + #HeaderString + CHAR(39) + ' UNION ALL SELECT '
END
ELSE
SET #DBAI = ' SELECT '
SET #DBAO = ' FROM ' + #Bank + ' AS T'
+ CASE WHEN #DBWhere IS NULL THEN '' ELSE ' WHERE (' + #Cash + ') AND 0 = 0' END
+ CASE WHEN #DBThere IS NULL THEN '' ELSE ' ORDER BY ' + #Risk END
-- Output where #DBUltra = 0 (Uses XP_CMDSHELL \ BCP)
IF #PCWrite IS NOT NULL AND #DBUltra = 0
BEGIN
SET #Wish = 'USE ' + DB_NAME() + #DBAI + #DBAU + #DBAO
SET #Work = 'BCP "' + #Wish + '" QUERYOUT "' + #PCWrite + '" -w -T -S "' + ##SERVERNAME + '" '
-- PRINT #Work
EXECUTE #Return = master.dbo.xp_cmdshell #Work, NO_OUTPUT
SET #Retain = ##ERROR
IF #Status = 0 SET #Status = #Retain
IF #Status = 0 SET #Status = #Return
IF #Status <> 0 GOTO ABORT
END
-- Output where #DBUltra = 1 (Uses Ole Automation)
IF #PCWrite IS NOT NULL AND #DBUltra = 1
BEGIN
IF #Status = 0 EXECUTE #Return = sp_OACreate 'Scripting.FileSystemObject', #Fuse OUTPUT
SET #Retain = ##ERROR
IF #Status = 0 SET #Status = #Retain
IF #Status = 0 SET #Status = #Return
IF #Status = 0 EXECUTE #Return = sp_OAMethod #Fuse, 'CreateTextFile', #File OUTPUT, #PCWrite, -1
SET #Retain = ##ERROR
IF #Status = 0 SET #Status = #Retain
IF #Status = 0 SET #Status = #Return
IF #Status <> 0 GOTO ABORT
END
SET #DBAI = 'DECLARE Records CURSOR GLOBAL FAST_FORWARD FOR' + #DBAI
IF #Status = 0 EXECUTE (#DBAI+#DBAU+#DBAO) SET #Return = ##ERROR
IF #Status = 0 SET #Status = #Return
OPEN Records
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
FETCH NEXT FROM Records INTO #Next
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
-- Header.
SET #HeaderDone = 0
WHILE ##FETCH_STATUS = 0 AND #Status = 0
BEGIN
IF #PCWrite IS NOT NULL AND #DBUltra = 1
BEGIN
-- Write header (FILE).
IF (#Header = 1) and (#HeaderDone = 0)
BEGIN
SET #Save = #HeaderString + CHAR(13) + CHAR(10)
IF #Status = 0 EXECUTE #Return = sp_OAMethod #File, 'Write', NULL, #Save
SET #HeaderDone = 1
END
-- Write the data (FILE).
SET #Save = #Next + CHAR(13) + CHAR(10)
IF #Status = 0 EXECUTE #Return = sp_OAMethod #File, 'Write', NULL, #Save
IF #Status = 0 SET #Status = #Return
END
IF #PCWrite IS NULL
BEGIN
-- Print header (TEXT).
IF (#Header = 1) and (#HeaderDone = 0)
BEGIN
PRINT #HeaderString + CHAR(13) + CHAR(10)
SET #HeaderDone = 1
END
PRINT #Next
END
FETCH NEXT FROM Records INTO #Next
SET #Retain = ##ERROR IF #Status = 0 SET #Status = #Retain
END
CLOSE Records DEALLOCATE Records
-- Close output file (Ole Automation)
IF #PCWrite IS NOT NULL AND #DBUltra = 1
BEGIN
EXECUTE #Return = sp_OAMethod #File, 'Close', NULL
IF #Status = 0 SET #Status = #Return
EXECUTE #Return = sp_OADestroy #File
IF #Status = 0 SET #Status = #Return
EXECUTE #Return = sp_OADestroy #Fuse
IF #Status = 0 SET #Status = #Return
END
ABORT: -- This label is referenced when OLE automation fails.
IF #Status = 1 OR #Status NOT BETWEEN 0 AND 50000 RAISERROR ('SaveDelimitedColumns Windows Error [%d]', 16, 1, #Status)
SET #Task = 'IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE name = ' + CHAR(39) + #DBAE + CHAR(39) + ') DROP TABLE ' + #DBAE
EXECUTE (#Task);
RETURN (#Status);
END;
Add the lines
SET #HeaderString = replace(#HeaderString, '[', '')
SET #HeaderString = replace(#HeaderString, ']', '')
right after the line
CLOSE Fields DEALLOCATE Fields
SELECT '['+C.name+']', C.colid, T.name, C.isnullable, C.iscomputed, C.length, C.prec, C.scale
Right there you added the [ ] to your column names, C.Name is the column name. Most times you can get away with not using the braces, unless your tables use reserved words for column names.
SELECT C.name, C.colid, T.name, C.isnullable, C.iscomputed, C.length, C.prec, C.scale
Alternatively you could trim them at the end, right after you CLOSE and DEALOCATE your Fields cursor, like this:
CLOSE Fields DEALLOCATE Fields
SET #HeaderString = replace(replace(#HeaderString, ']', ''), '[', '')
I don't know why my code is trying to convert the query within the variable to data type INT. And what's even stranger is that I got the code working fine on Linqpad. Then I pasted the code into Report Builder 3.0 and tested it again within the query view, which worked fine. Next, I went to report view and ran it once. This worked fine as well. However, once I ran it a second time with a new specified parameter, it threw an error and told me to check on the local machine.
The code:
DECLARE #item varchar(50) = '%'
DECLARE #lp varchar(50) = '1231888'
DECLARE #loc varchar(10) = '%'
DECLARE #lot varchar(30) = '%'
DECLARE #trans_type varchar(2) = '%'
DECLARE #desc varchar(20) = '%'
DECLARE #whse varchar(4) = '%'
DECLARE #u_m varchar(20) = '%'
DECLARE #emp_num varchar(20) = '%'
DECLARE #ref_num varchar(20) = '%'
DECLARE #fglot varchar(20) = '%'
DECLARE #shift varchar(20) = '%'
DECLARE #truckid varchar(20) = '%'
DECLARE #trans_date datetime2 = NULL
DECLARE #trans_date_string varchar(10) = CAST(#trans_date AS nvarchar(10))
DECLARE #shiftdate datetime2 = NULL
DECLARE #shiftdate_string varchar(10) = CAST(#shiftdate AS nvarchar(10))
DECLARE #createdate datetime2 = NULL
DECLARE #createdate_string varchar(19) = CAST(#createdate AS nvarchar(19))
DECLARE #ref_line_suf int = 4
DECLARE #ref_line_suf_string varchar(2) = CAST(#ref_line_suf AS varchar(2))
DECLARE #qty decimal = NULL
DECLARE #qty_string varchar(30) = CAST(#qty AS varchar(30))
--Define query
DECLARE #query as nvarchar(2500)
SET #query =
'SELECT TOP (10000)
*
FROM
isw_lptrans AS t
WHERE
1=1'
+ CASE
WHEN #item = '%' OR #item = ''
THEN ''
ELSE ' AND t.item LIKE ' + '''' + #item + ''''
END
+ CASE
WHEN #lp = '%' OR #lp = ''
THEN ''
ELSE ' AND t.lp_num LIKE ' + '''' + '%' + #lp + '%' + ''''
END
+ CASE
WHEN #loc = '%' OR #loc = ''
THEN ''
ELSE ' AND t.loc = ' + '''' + #loc + ''''
END
+ CASE
WHEN #lot = '%' OR #lot = ''
THEN ''
ELSE ' AND t.lot = ' + '''' + #lot + ''''
END
+ CASE
WHEN #trans_type = '%' OR #trans_type = ''
THEN ''
ELSE ' AND t.trans_type = ' + '''' + #trans_type + ''''
END
+ CASE
WHEN #desc = '%' OR #desc = ''
THEN ''
ELSE ' AND t.description LIKE ' + '''' + '%' + #desc + '%' + ''''
END
+ CASE
WHEN #whse = '%' OR #whse = ''
THEN ''
ELSE ' AND t.whse = ' + '''' + #whse + ''''
END
+ CASE
WHEN #u_m = '%' OR #u_m = ''
THEN ''
ELSE ' AND t.u_m = ' + '''' + #u_m + ''''
END
+ CASE
WHEN #emp_num = '%' OR #emp_num = ''
THEN ''
ELSE ' AND t.emp_num = ' + '''' + #emp_num + ''''
END
+ CASE
WHEN #ref_num = '%' OR #ref_num = ''
THEN ''
ELSE ' AND t.ref_num = ' + '''' + #ref_num + ''''
END
+ CASE
WHEN #fglot = '%' OR #fglot = ''
THEN ''
ELSE ' AND t.fglotcode = ' + '''' + #fglot + ''''
END
+ CASE
WHEN #shift = '%' OR #shift = ''
THEN ''
ELSE ' AND t.uf_shift = ' + '''' + #shift + ''''
END
+ CASE
WHEN #truckid = '%' OR #truckid = ''
THEN ''
ELSE ' AND t.uf_truckid = ' + '''' + #truckid + ''''
END
+ CASE
WHEN #trans_date IS NULL
THEN ''
ELSE ' AND t.trans_date = ' + '''' + #trans_date_string + ''''
END
+ CASE
WHEN #shiftdate IS NULL
THEN ''
ELSE ' AND t.uf_shift_start_date = ' + '''' + #shiftdate_string + ''''
END
+ CASE
WHEN #createdate IS NULL
THEN ''
ELSE ' AND (t.createdate BETWEEN ' + '''' + CAST(DATEADD(hh, -24, #createdate) AS varchar(19)) + '''' + ' AND ' + '''' + CAST(DATEADD(hh, 24, #createdate) AS varchar(19)) + '''' + ' ) '
END
+ CASE
WHEN #ref_line_suf IS NULL
THEN ''
ELSE ' AND t.ref_line_suf = ' + #ref_line_suf_string
END
+ CASE
WHEN #qty IS NULL
THEN ''
ELSE ' AND t.qty = ' + #qty_string
END
;
print #query
EXEC sp_executesql #query
Screenshot of error:
Query print-out with the parameters that create a problem (note: this is from Linqpad, where there is no problem. The problem occurs in Report Builder 3.0):
SELECT TOP (10000)
*
FROM
isw_lptrans AS t
WHERE
1=1 AND t.lp_num LIKE '%1231888%' AND t.ref_line_suf = 4
This should work for 2008 now.
DECLARE #item varchar(50) = '1'
DECLARE #lp varchar(50) = '1231888'
DECLARE #loc varchar(10) = '2'
DECLARE #lot varchar(30) = '3'
DECLARE #trans_type varchar(2) = '4'
DECLARE #desc varchar(20) = '5'
DECLARE #whse varchar(4) = '6'
DECLARE #u_m varchar(20) = '7'
DECLARE #emp_num varchar(20) = '8'
DECLARE #ref_num varchar(20) = '9'
DECLARE #fglot varchar(20) = '10'
DECLARE #shift varchar(20) = '11'
DECLARE #truckid varchar(20) = '12'
DECLARE #trans_date datetime2 = '2015-01-01'
DECLARE #shiftdate datetime2 = '2015-01-01'
DECLARE #createdate datetime2 = '2015-01-01'
DECLARE #ref_line_suf int = 4
DECLARE #qty decimal(15,5) = 5.2678
--Define query
DECLARE #query NVARCHAR(MAX)
SET #query =
'SELECT TOP (10000)
*
FROM isw_lptrans AS t
WHERE 1=1'
;
SET #query =
#query
+ISNULL(' AND t.item LIKE '''+CASE WHEN #item IN ('','%') THEN NULL ELSE #item END+'''','')
+ISNULL(' AND t.lp LIKE ''%'+CASE WHEN #lp IN ('','%') THEN NULL ELSE #lp END+'%''','')
+ISNULL(' AND t.loc = '''+CASE WHEN #loc IN ('','%') THEN NULL ELSE #loc END+'''','')
+ISNULL(' AND t.lot = '''+CASE WHEN #lot IN ('','%') THEN NULL ELSE #lot END+'''','')
+ISNULL(' AND t.trans_type = '''+CASE WHEN #trans_type IN ('','%') THEN NULL ELSE #trans_type END+'''','')
+ISNULL(' AND t.desc LIKE ''%'+CASE WHEN #desc IN ('','%') THEN NULL ELSE #desc END+'%''','')
+ISNULL(' AND t.whse = '''+CASE WHEN #whse IN ('','%') THEN NULL ELSE #whse END+'''','')
+ISNULL(' AND t.u_m = '''+CASE WHEN #u_m IN ('','%') THEN NULL ELSE #u_m END+'''','')
+ISNULL(' AND t.emp_num = '''+CASE WHEN #emp_num IN ('','%') THEN NULL ELSE #emp_num END+'''','')
+ISNULL(' AND t.ref_num = '''+CASE WHEN #ref_num IN ('','%') THEN NULL ELSE #ref_num END+'''','')
+ISNULL(' AND t.fglot = '''+CASE WHEN #fglot IN ('','%') THEN NULL ELSE #fglot END+'''','')
+ISNULL(' AND t.shift = '''+CASE WHEN #shift IN ('','%') THEN NULL ELSE #shift END+'''','')
+ISNULL(' AND t.truckid = '''+CASE WHEN #truckid IN ('','%') THEN NULL ELSE #truckid END+'''','')
+ISNULL(' AND t.trans_date = '''+CONVERT(VARCHAR(10),#trans_date)+'''','')
+ISNULL(' AND t.uf_shift_start_date = '''+CONVERT(VARCHAR(10),#shiftdate)+'''','')
+ISNULL(' AND t.createdate BETWEEN '''+CONVERT(VARCHAR(19),DATEADD(hour,-24,#createdate))+''' AND '''+CONVERT(VARCHAR(19),DATEADD(hour,24,#createdate))+'''','')
+ISNULL(' AND t.ref_line_suf = '+CONVERT(VARCHAR(2),#ref_line_suf),'')
+ISNULL(' AND t.qty = '+CONVERT(VARCHAR(30),#qty)+'''','')
;
print #query;
I get the error 'Too many arguments specified' but cannot find the problem
Any help would be greatly appreciated
The 3 parameters are specified at the begin of the procedure
DECLARE
#WhereStatment nvarchar(500),
#ParamList nvarchar(500) = N'#p1 int, #p2 varchar(256), #p3 int'
SET #WhereStatment = ''
-- Check for Status Filter
IF #StatusFilter <> 'All'
SET #WhereStatment = #WhereStatment + ' EntryStatus = #StatusFilter'
ELSE
BEGIN
SET #StatusFilter = 'Invoiced (Complete)'
SET #WhereStatment = #WhereStatment + ' EntryStatus <> #StatusFilter'
END
-- Check for User Filter
IF #UserFilter > 0
SET #WhereStatment = #WhereStatment + ' AND EobID = #UserFilter'
-- Check for Warehouse Filter
IF #WarehouseFilter > 0
SET #WhereStatment = #WhereStatment + ' AND WarehouseNumber = #WarehouseFilter'
-- Add WhereStatement
Set #WhereStatment = '
SELECT
tblWCS_SQE_Entries.RowID, SaleNum, tblWCS_Company_UserAccounts.Fullname, Ets
FROM tblWCS_SQE_Entries
INNER JOIN tblWCS_Company_UserAccounts
ON tblWCS_SQE_Entries.EobID = tblWCS_Company_UserAccounts.RowID
WHERE
'
+ #WhereStatment;
EXEC sp_sqlexec #WhereStatment, #ParamList,
#p1 = #UserFilter,
#p2 = #StatusFilter,
#p3 = #WarehouseFilter
sp_sqlexec stored procedure indeed has only one parameter. Probably you want sp_executesql instead.
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = '
SELECT tblWCS_SQE_Entries.RowID, SaleNum, tblWCS_Company_UserAccounts.Fullname, Ets
FROM dbo.tblWCS_SQE_Entries
JOIN dbo.tblWCS_Company_UserAccounts ON tblWCS_SQE_Entries.EobID = tblWCS_Company_UserAccounts.RowID
WHERE '
+ CASE WHEN #StatusFilter = 'All'
THEN ' EntryStatus <> ''Invoiced (Complete)'''
ELSE ' EntryStatus = #StatusFilter'
END
+ CASE WHEN #WarehouseFilter > 0 THEN ' AND WarehouseNumber = #WarehouseFilter' ELSE '' END
+ CASE WHEN #UserFilter > 0 THEN ' AND EobID = #UserFilter' ELSE '' END
EXEC sys.sp_executesql #SQL
, N'#p1 int, #p2 varchar(256), #p3 int'
, #p1 = #UserFilter
, #p2 = #StatusFilter
, #p3 = #WarehouseFilter
I've a Dynamic SQL that is required to be optimized. I need to make CASE Expression Dynamic. I've a list of ATTRIBUTE_LIST & SCENARIO_LIST, that are provided below. I wrote a Function to get them Dynamically. How can I replace Three CASE Expression and make it Dynamic? I'm trying to avoid hard coding.
SET #ATTRIBUTE_LIST = 'symbol_type, currency, performing_status' -- INPUTS
SET #SCENARIO_LIST = 'historicalsimulation_1day_end_10dec2013, historicalsimulation_1day_end_11dec2013'
SELECT CASE
WHEN (GROUPING(Scenario_Name) = 1) THEN ''ALL''
WHEN (Scenario_Name = ''[BaseCase]'') THEN ''BaseCase''
ELSE ISNULL(Scenario_Name, '''')
END AS Scenario_Name,
CASE
WHEN (GROUPING(Symbol_Type) = 1) THEN ''ALL''
ELSE ISNULL(Symbol_Type, '''')
END AS Symbol_Type,
CASE
WHEN (GROUPING(Currency) = 1) THEN ''ALL''
ELSE ISNULL(Currency, '''')
END AS Currency,
CASE
WHEN (GROUPING(Performing_Status) = 1) THEN ''ALL''
ELSE ISNULL(Performing_Status, '''') \
END AS Performing_Status,
SUM(Value) AS ScenarioValue
FROM [20151005_171003_UserName_NT-22_Analysis_Tue] o
LEFT JOIN [20151005_171003_UserName_NT-22_Analysis_Tue_Position_Data] pld
ON o.Position_Unique_Identifier=pld.Position_Unique_Identifier
GROUP BY ' + #ATTRIBUTE_LIST + ' WITH CUBE) AS DATA
PIVOT ( Sum(scenariovalue)
FOR scenario_name IN (' + #SCENARIO_LIST + ')'
It appears you are using SQL Server. Here's a brute-force way of looping over your attributes and building a series of case expressions:
declare #cases nvarchar(max) = '';
declare #l varchar(max) = #ATTRIBUTE_LIST + ',';
declare #ofs int = 0;
declare #pos int = charindex(',', #l, #ofs + 1);
while #pos > 0
begin
if #cases <> '' set #cases = #cases + ',';
set #cases = #cases +
replace('
CASE WHEN (GROUPING(<COL>) = 1) THEN ''ALL''
ELSE ISNULL(<COL>, '''')
END AS <COL>',
'<COL>', substring(#l, #ofs + 1, #pos - #ofs - 1)
);
set #ofs = #pos;
set #pos = charindex(',', #l, #ofs + 1);
end
select #cases;
I have the following SQL to format a US address into each line for a mailing address but it is rather ugly. Is there a better way to solve this problem or does it have to be this ugly? Also, the problem with this code is that it always ends up with an extra new line at the end.
declare #NL varchar(2);
set #NL = char(13) + char(10);
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress
from Address
where Id = 1
If your Sql Server Settings are such that NULL + varchar returns NULL (SET CONCAT_NULL_YIELDS_NULL (Transact-SQL)), this can help.
DECLARE #Address TABLE(
ID INT,
AttentionLine VARCHAR(50),
Recipient VARCHAR(50),
AddlAddrLine VARCHAR(50),
DeliveryAddr VARCHAR(50),
LastLine VARCHAR(50),
Country VARCHAR(50)
)
declare #NL varchar(2);
set #NL = char(13) + char(10);
INSERT INTO #Address SELECT 1, NULL, '1', NULL, '2', NULL, '3'
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress ,
RTRIM(coalesce(AttentionLine + #NL,'')) +
RTRIM(coalesce(Recipient + #NL,'')) +
RTRIM(coalesce(AddlAddrLine + #NL,'')) +
RTRIM(coalesce(DeliveryAddr + #NL,'')) +
RTRIM(coalesce(LastLine + #NL,'')) +
RTRIM(coalesce(Country + #NL,''))
from #Address
where Id = 1
I realize this is an old question, but there is a new solution to this problem: the CONCAT_WS() function, which is new for SQL Server 2017 (it's also available for Azure SQL Database).
SELECT CONCAT_WS (
CHAR(13) + CHAR(10), --Separator
NULLIF(AttentionLine, ''),
NULLIF(Recipient, ''),
NULLIF(AddlAddrLine, ''),
NULLIF(DeliveryAddr, ''),
NULLIF(LastLine, ''),
NULLIF(Country, '')
)
AS FormattedMailingAddress
FROM Address
WHERE Id = 1
NULL values are ignored by the function, which is why NULLIF is used with each argument/parameter in this example. (When the argument/parameter evaluates to NULL, the separator won't be added either). Here's a short blog post with some more details: New For SQL Server 2017: T-SQL Function CONCAT_WS