SQL Server stored procedure - sql

I want it to count then if #intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?
#FiscalYear int,
#SchoolID int,
#Status int
AS
BEGIN
SET NOCOUNT ON;
declare #sqlstr varchar(2000)
declare #intCount int
set #intCount = 0
set #sqlstr = 'Select #intCount = Count(*)
From PrivateSchool left outer join Attachment on Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
inner join FiscalYearPrivateSchool fp ON fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
Where (FiscalYear = '+convert(varchar, #FiscalYear)+') AND (PrivateSchool.IsActive = 1)'
IF (#SchoolID != -1)
SET #sqlstr = #sqlstr + ' AND SchoolID ='+ convert(varchar, #SchoolID)
IF (#Status = -1)
SET #sqlstr = #sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else IF (#Status = 1)
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID is Null'
If (#intCount > 0)
BEGIN
set #sqlstr= 'Select SchoolName as School,
(Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
ELSE ''Not Uploaded'' END) AS Status,
COUNT(Attachment.PrivateSchoolID) AS [Count]
From PrivateSchool left outer join Attachment on Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
inner join FiscalYearPrivateSchool fp ON fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
Where (FiscalYear = '+convert(varchar, #FiscalYear)+') AND (PrivateSchool.IsActive = 1)'
IF (#SchoolID != -1)
SET #sqlstr = #sqlstr + ' AND SchoolID ='+ convert(varchar, #SchoolID)
IF (#Status = -1)
SET #sqlstr = #sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else IF (#Status = 1)
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID is Null'
SET #sqlstr = #sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
SET #sqlstr = #sqlstr + ' Order By SchoolName'
EXEC(#sqlstr)
END
ELSE
Select 'No Data Found' as 'FileUpload'
END

You need:
EXEC sp_executesql #sqlstr, N'#intCount INT OUTPUT', #intCount = #intCount OUTPUT;
IF (#intCount > 0)
BEGIN
....
END
You'll also need to make #sqlstr NVARCHAR(2000) and add set it to N'SELECT ...' as opposed to 'SELECT ...' - that leading N can be important.

The problem is:
declare #intCount int
set #intCount = 0
...
<a bunch of code where #intcount doesn't change>
If (#intCount > 0)
It's always going to be 0.

Your issue is one of scope. The EXEC(#sqlstr) command doesn't have access to the #intcount variable in your stored procedure. I would bet if you ran this code in a query window, it would tell you to declare #intcount.
Listen to YUCK and rewrite this to avoid dynamic SQL, and then your SELECT will be able to set the #intcount variable.

Related

saveDelimitedColumns

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, ']', ''), '[', '')

SQL Server dynamic parameters join stored procedure

This my stored procedure and parameters but I need to do dynamic search
SELECT
dbo.Invoices.*,
dbo.Vessels.Name AS VesselName,
dbo.Companies.Name AS CompanyName,
dbo.InvoiceTypes.Name AS InvoiceTypeName,
dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.InvoiceItems.InvoiceItemID
FROM
dbo.Invoices
LEFT JOIN dbo.Vessels ON
dbo.Invoices.VesselID = dbo.Vessels.VesselID
INNER JOIN dbo.Companies ON
dbo.Invoices.CompanyID = dbo.Companies.CompanyID
LEFT JOIN dbo.InvoiceTypes ON
dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID
LEFT JOIN dbo.InvoiceVsInvoiceItems ON
dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID
LEFT JOIN dbo.InvoiceItems ON
dbo.InvoiceVsInvoiceItems.InvoiceItemID = dbo.InvoiceItems.InvoiceItemID
PARAMETERS
#InvoiceItemID int,
#InvoiceTypeID int,
#VesselID int,
#PaidByID int,
#InvoiceNo NVarchar(50),
#CompanyID int,
#chkSearchInvoiceDate bit,
#chkSearchIsDueDate bit,
#chkSearchIsPaid bit,
#chkSearchReceived bit,
#chkSearchAmount bit,
#chkSearchInvoiceType bit,
#InvoiceFromDate DateTime,
#InvoiceToDate DateTime,
#FromDueDate DateTime,
#ToDueDate DateTime,
#FromAmount decimal(18,4),
#ToAmount decimal(18,4)
But I tried it what do I do when there are multiple where? I could not :(
Thank you
Declare #SQLQuery AS NVarchar(4000)
Declare #ParamDefinition AS NVarchar(2000)
Set #SQLQuery = 'SELECT dbo.Invoices.*, dbo.Vessels.Name AS VesselName, dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName,
dbo.InvoiceItems.Name AS InvoiceItemName, dbo.InvoiceItems.InvoiceItemID'
If #InvoiceItemID Is Not Null
Set #SQLQuery = #SQLQuery + 'FROM dbo.Invoices LEFT JOIN dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceItemID = dbo.InvoiceItems.InvoiceItemID WHERE dbo.InvoiceVsInvoiceItems.InvoiceItemID = #InvoiceItemID'
If #VesselID Is Not Null
Set #SQLQuery = #SQLQuery + 'LEFT JOIN dbo.Vessels ON dbo.Vessels.VesselID = dbo.Invoices.VesselID WHERE dbo.Invoices.VesselID = #VesselID'
If #InvoiceNo Is Not Null
Set #SQLQuery = #SQLQuery + 'WHERE dbo.Invoices.InvoiceNo = #InvoiceNo'
If #CompanyID Is Not Null
Set #SQLQuery = #SQLQuery + 'WHERE dbo.Invoices.CompanyID = #CompanyID'
If #chkSearchInvoiceDate > 0
Set #SQLQuery = #SQLQuery + 'WHERE Between #InvoiceFromDate and #InvoiceToDate'
If #chkSearchIsDueDate > 0
Set #SQLQuery = #SQLQuery + 'WHERE Between #FromDueDate and #ToDueDate'
If #chkSearchIsPaid > 0
Set #SQLQuery = #SQLQuery + 'WHERE dbo.Invoices.PaidBy = #PaidBy'
If #chkSearchReceived > 0
Set #SQLQuery = #SQLQuery + 'WHERE dbo.Invoices.InvoiceNo = #InvoiceNo'
If you want to be able to use multiple parameters in the where clause at the same time you can add them like this:
Declare #SQLQuery AS NVarchar(4000)
Declare #ParamDefinition AS NVarchar(2000)
Set #SQLQuery = '
SELECT
dbo.Invoices.*,
dbo.Vessels.Name AS VesselName,
dbo.Companies.Name AS CompanyName,
dbo.InvoiceTypes.Name AS InvoiceTypeName,
dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.InvoiceItems.InvoiceItemID
FROM dbo.Invoices
LEFT JOIN dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceItemID = dbo.InvoiceItems.InvoiceItemID
LEFT JOIN dbo.Vessels ON dbo.Vessels.VesselID = dbo.Invoices.VesselID
WHERE 1=1 '
If #InvoiceItemID Is Not Null
Set #SQLQuery = #SQLQuery + ' AND dbo.InvoiceVsInvoiceItems.InvoiceItemID = #InvoiceItemID'
If #VesselID Is Not Null
Set #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID = #VesselID'
If #InvoiceNo Is Not Null
Set #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceNo = #InvoiceNo'
If #CompanyID Is Not Null
Set #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = #CompanyID'
If #chkSearchInvoiceDate > 0
Set #SQLQuery = #SQLQuery + ' AND InvoiceDate Between #InvoiceFromDate and #InvoiceTODate'
If #chkSearchIsDueDate > 0
Set #SQLQuery = #SQLQuery + ' AND IsDueDate Between #FromDueDate and #ToDueDate'
If #chkSearchIsPaid > 0
Set #SQLQuery = #SQLQuery + ' AND dbo.Invoices.PaidBy = #PaidByID'
If #chkSearchReceived > 0
Set #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceNo = #InvoiceNo'

Dynamic TSQL Query output as XML

I have a dynamic TSQL query that is working perfectly. However, before I had it dynamic like this I was returning it as an XML output.
How can I do the same with my output now? I need the results in an XML format.
ALTER PROCEDURE [dbo].[empowermentFetchSubmissions2]
#category INT=NULL, #department INT=NULL, #startDate DATE=NULL, #endDate DATE=NULL, #empID VARCHAR (60)=NULL, #submissionID INT=NULL, #inVoting INT=NULL, #pastWinners INT=NULL
AS
DECLARE #sSQL AS NVARCHAR (3000),
#Where AS NVARCHAR (1000) = ' (1=1) ';
BEGIN
SET NOCOUNT ON;
BEGIN
SET #sSQL = 'SELECT A.[submissionID],
A.[subEmpID],
A.[nomineeEmpID],
A.[nomineeDepartment],
CONVERT (VARCHAR (10), A.[submissionDate], 101) AS submissionDate,
A.[situation],
A.[task],
A.[action],
A.[result],
A.[timestamp],
A.[statusID],
A.[approver],
A.[approvalDate],
B.[FirstName] + '' '' + B.[LastName] AS nomineeName,
B.[ntid] AS nomineeNTID,
B.[qid] AS nomineeQID,
C.[FirstName] + '' '' + C.[LastName] AS submitName,
C.[ntid] AS submitNTID,
D.[categoryName],
(SELECT CAST
(CASE WHEN EXISTS (SELECT TOP (1) submissionID
FROM empowermentEntries
WHERE sessionID = (SELECT TOP (1) sessionID
FROM empowermentSessions
WHERE status = 1
AND CAST(GETDATE() as date) >= startDate
AND CAST(GETDATE() as date) <= endDate ) AND submissionID = A.[submissionID])
THEN ''true''
ELSE ''false''
END AS XML) AS inVoting)
FROM empowermentSubmissions AS A
INNER JOIN
empTable AS B
ON A.[nomineeEmpID] = B.[empID]
INNER JOIN
empTable AS C
ON A.[subEmpID] = C.[empID]
INNER JOIN
empowermentCategories AS D
ON A.[categoryID] = D.[catID]';
IF #category IS NOT NULL
SET #Where = #Where + ' AND A.[categoryID] = #_category';
IF #department IS NOT NULL
SET #Where = #Where + ' AND A.[nomineeDepartment] = #_department';
IF #startDate IS NOT NULL
SET #Where = #Where + ' AND A.[submissionDate] >= #_startDate';
IF #endDate IS NOT NULL
SET #Where = #Where + ' AND A.[submissionDate] <= #_endDate';
IF #empID IS NOT NULL
SET #Where = #Where + ' AND A.[nomineeEmpID] = #_empID';
IF #submissionID IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] = #_submissionID';
IF #inVoting IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] IN (SELECT submissionID
FROM empowermentEntries
WHERE sessionID = (SELECT TOP (1) sessionID
FROM empowermentSessions
WHERE status = 1
AND CAST(GETDATE() as date) >= startDate
AND CAST(GETDATE() as date) <= endDate )
AND submissionID = A.[submissionID])';
IF #pastWinners IS NOT NULL
SET #Where = #Where + ' AND A.[submissionID] IN (SELECT E.[submissionID]
FROM empowermentEntries as E
JOIN empowermentWinners as F
ON E.[entryID] = F.[entryID]
WHERE submissionID = A.[submissionID])';
IF LEN(#Where) > 0
SET #sSQL = #sSQL + ' WHERE ' + #Where;
EXECUTE sp_executesql #sSQL, N'#_category INT, #_department INT, #_startDate DATE, #_endDate DATE, #_empID VARCHAR(60), #_submissionID INT, #_inVoting INT, #_pastWinners INT', #_category = #category, #_department = #department, #_startDate = #startDate, #_endDate = #endDate, #_empID = #empID, #_submissionID = #submissionID, #_inVoting = #inVoting, #_pastWinners = #pastWinners;
END
END
You need to take your existing Dynamic SQL, added the FOR XML... to the end, wrap that in parenthesis, and set that value to a variable which is used as OUTPUT for the sp_executesql. For example:
DECLARE #SQL NVARCHAR(MAX),
#Results XML;
SET #SQL = N'
SET #Out = (SELECT * FROM sys.objects FOR XML AUTO);
';
EXEC sp_executesql #SQL, N'#Out XML OUTPUT', #Out = #Results OUTPUT;
SELECT #Results;
So declare a new variable at the top for:
DECLARE #Results XML;
Then just before your EXECUTE sp_executesql #sSQL... line, do the following:
SET #sSQL = N'SET #Results = (' + #sSQL + N' FOR XML {xml options});';
Then update your param spec for sp_executesql to include, at the end:
N'#_category INT, ..., #Results XML OUTPUT'
And add the following to the end of the sp_executesql:
#_category = #category, ..., #Out = #Results OUTPUT

SQL Update command with various variables

I have table like:
Items
ID(int)
Name(varchar)
Date(DateTime)
Value(int)
I would like to write SQL Command which will update only these values, which are not null
Pseudo code of what I would like to do:
UPDATE Items
SET
IF #NewName IS NOT NULL
{
Items.Name = #NewName
}
IF #NewDate IS NOT NULL
{
Items.Date = #NewDate
}
IF #newValue IS NOT NULL
{
Items.Valie = #NewValue
}
WHERE Items.ID = #ID
Is it possible to write query like this?
UPDATE Items
SET Name = ISNULL(#NewName,Name),
[Date] = ISNULL(#NewDate,[Date]),
Value = ISNULL(#NewValue,Value)
WHERE ID = #ID
You cannt use if statement in update you can use below query for update on condition
'UPDATE Items
SET
Items.Name = (case when #NewName is not null then #NewName else end) ,
Items.Date = (case when #NewDate is not null then #newDate else end ),
Items.Valie = (case when #Valie is not null then #Valie else end )
WHERE Items.ID = #ID'
You can make something like this:
declare #sql varchar(1000)
set #sql = 'UPDATE Items SET '
IF #NewName IS NOT NULL
#sql = #sql + 'Items.Name = ' + #NewName
IF #NewDate IS NOT NULL
#sql = #sql + 'Items.Date = ' + #NewDate
IF #newValue IS NOT NULL
#sql = #sql + 'Items.Valie = ' + #NewValue
#sql = #sql + 'WHERE Items.ID = ' + #ID
exec(#sql)

Invalid Column Name '#FileName-- value'

I am getting 'Invalid Column Name '#FileName-- value'' ERROR WHILE executing below stored procedure. I tried to find the root cause of the issue with no luck...Please suggest me where i am wrong.
ALTER PROCEDURE [dbo].[usp_ICLExtract_GetFile]
#FileName Varchar(50),
#Image_Path Varchar(50) Output,
#FIleNameList varchar(4096) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #strProcName varchar(255)
SET #strProcName = 'usp_ICLExtract_GetFile'
DECLARE #strSQL1 varchar(1024), #strSQL2 varchar(1024)
DECLARE #strFileName Varchar(50)
DECLARE #intErrorReturn int
SET #intErrorReturn = 0
SET #FileNameList = ''
SET #Image_Path = ''
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ' + #FileName --This line cause error
/*==============================================================================
* Run the query'
*==============================================================================*/
SET #strSQL2 = 'DECLARE curCategory INSENSITIVE SCROLL CURSOR FOR ' + #strSQL1
EXEC(#strSQL2)
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
OPEN curCategory
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
FETCH NEXT FROM curCategory INTO #strFileName
WHILE (##FETCH_STATUS <> -1)
BEGIN
SET #FileNameList = #FileNameList + #strFileName + ';'
SET #Image_Path = #Image_Path + 1
FETCH NEXT FROM curCategory INTO #strFileName
END
CLOSE curCategory
DEALLOCATE curCategory
RETURN(0)
usp_ICLExtract_GetFile_Error:
RETURN(#intErrorReturn)
END
replace line with this
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName +'''
Change your query to this:
N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter
INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID =
[tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName + ''''
you have to pass value between apostrophes '.