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'
Related
Example:
Lr_id
11
12
13
Ref_no
11
IN Table if match found in ref_no so display record of 12 otherwise 11.
Same Id like lr_id = 11 & Ref_no=11 so i want display record of lr_id =12 because ref_no = 11 assign to lr_id. Otherwise display as it is lr_id record.
SQL QUERY:
ALTER Procedure [dbo].[Track_LR_history]
#GCno as varchar(100),
#reference_no as varchar(100)
AS
declare #qry as varchar(max)
declare #cond as varchar(max)
declare #finalqry as varchar(max)
set #qry = 'SELECT l.lr_id AS GCno, l.creation_dt AS Date, Party.ConsignorName AS Consignor, Party.ConsigneeName AS Consignee, offi.branch_name AS Bookingbranch, '
set #qry = #qry + 'dbo.TBL_BRANCH.branch_name AS CurrentBranch, tost.branch_name AS DestinationBranch, TBL_APP_LIST_ELM_1.name AS CollType, '
set #qry = #qry + ' dbo.TBL_APP_LIST_ELM.name AS Deltype, TBL_APP_LIST_ELM_2.name AS PayType, l.reporting_date AS ReportingDate, case when isnull(l.stax_applicable_to2app_elm,0) =268435545 then isnull(chgamt.Booking,0) + isnull(l.ser_tax,0) else isnull(chgamt.Booking,0) end AS BookingAmt, '
set #qry = #qry + ' l.invoice_no AS Invno, l.lr_total_qty AS Qty, l.lr_total_weight AS Weight, l.entry_date, l.reference_no,dbo.TBL_BUS_CUST.cust_name AS FranchiseName, l.challan_no '
set #qry = #qry + ' FROM dbo.TBL_LR_HEAD AS l INNER JOIN dbo.TBL_BUS_CUST AS cr ON l.lr_cor2bc_cust = cr.row_id INNER JOIN '
set #qry = #qry + ' dbo.TBL_BUS_CUST AS ce ON l.lr_con2bc_cust = ce.row_id INNER JOIN dbo.TBL_BRANCH AS offi ON l.lr_frm2branch = offi.row_id INNER JOIN '
set #qry = #qry + ' dbo.TBL_BRANCH AS tost ON l.lr_to2branch = tost.row_id INNER JOIN dbo.TBL_BRANCH ON l.lr_current_br2site = dbo.TBL_BRANCH.row_id INNER JOIN '
set #qry = #qry + ' dbo.TBL_APP_LIST_ELM ON l.lr_del_typ2app_elm = dbo.TBL_APP_LIST_ELM.row_id INNER JOIN dbo.TBL_APP_LIST_ELM AS TBL_APP_LIST_ELM_1 ON l.lr_coll_typ2coll_typ = TBL_APP_LIST_ELM_1.row_id INNER JOIN '
set #qry = #qry + ' dbo.TBL_APP_LIST_ELM AS TBL_APP_LIST_ELM_2 ON l.lr_payment_type2app_elm = TBL_APP_LIST_ELM_2.row_id LEFT OUTER JOIN '
set #qry = #qry + ' dbo.TBL_BUS_CUST ON l.lr_franchise2bus_cust = dbo.TBL_BUS_CUST.row_id Left outer join'
set #qry = #qry + ' dbo.TBL_USER WITH (NOLOCK) ON l.lr_create2user = dbo.TBL_USER.row_id left outer join (select SUM(dbo.TBL_LR_CHARGES.amount) aS Booking,lr_chrg_item2lr_head from TBL_LR_CHARGES WITH (NOLOCK) where '
set #qry = #qry + ' dbo.TBL_LR_CHARGES.lr_chrg_bp2app_elm in ( 268435565) '
set #qry = #qry + ' AND lr_chrg_hd2chrg_hd <> 268435605 and lr_chrg_hd2chrg_hd <> 268435606 '
set #qry = #qry + ' and lr_chrg_hd2chrg_hd <> 268435607 and lr_chrg_hd2chrg_hd <> 268435608 and '
set #qry = #qry + ' lr_chrg_hd2chrg_hd <> 268435609 group by lr_chrg_item2lr_head) as chgamt on chgamt.lr_chrg_item2lr_head = l.row_id '
set #qry = #qry + ' left outer join View_LrConsrConse Party with (nolock) ON Party.Row_id = L.Row_id '
if #GCno<>''
begin
set #cond= ' where l.lr_id = '''+ #GCno +''''
--set #cond= ' where l.lr_id = '''+ #GCno +'+ OR +'+(select lr_id from TBL_LR_HEAD where reference_no=#reference_no)+''
end
if #reference_no<>''
begin
if #cond='' or #cond is null
begin
set #cond= ' where l.reference_no = '''+ #reference_no +''''
end
else
begin
set #cond= #cond + ' and l.reference_no = '''+ #reference_no +''''
end
end
exec (#qry + #cond)
Thank you.
I will go out on a limb and attempt an answer. It looks like you want to use the value from the Ref_no column if present (not NULL), otherwise use the value from the lr_id column. The COALESCE function does precisely this. Consider this query:
SELECT COALESCE(Ref_no, lr_id)
FROM yourTable
I have written a stored procedure like this
ALTER PROCEDURE [dbo].[spLoadPendingPaymentSheetByFilter] --'2015-04-01','2015-04-02','Select-One','Select-One','Select-One',''
#FromDate as datetime,
#ToDate as datetime,
#Status as nvarchar(50),
#Remarks as nvarchar(50),
#Paymenttype as nvarchar(50),
#BillID as nvarchar(50)
AS
Declare #Where as nvarchar(max)
set #Where = '( MenifestDate BETWEEN ''' + CONVERT(VARCHAR(10),#FromDate, 101) + ''' and ''' + CONVERT(VARCHAR(10),#ToDate, 101) + ''' )'
if(#Status <> 'Select-One')
set #Where = 'Status = '+ #Status
if(#Remarks <> 'Select-One')
set #Where = #Where + 'and Remarks = '+ #Remarks
if(#Paymenttype <> 'Select-One')
set #Where = #Where + 'and PaymentType = ' + #Paymenttype
if(#BillID <> '')
set #Where = #Where + 'and BillID = '+ #BillID
Declare #SelectString as nvarchar(1000)
set #SelectString = 'SELECT MasterID,BillID, MenifestDate, FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType
FROM tblMenifest
WHERE ' + #Where
exec #SelectString
When I execute it I got this error
The name 'SELECT MasterID,BillID, MenifestDate, FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType FROM tblMenifest WHERE ( MenifestDate BETWEEN '04/01/2015' and '04/02/2015' )' is not a valid identifier
The MenifestDate column datatype is datetime.
I believe that you want to put EXEC(#SelectString) rather than exec #SelectString.
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
I'm got trouble with paging on SQL server 2005 which run query 2 times (get data and total rows). My demo proc below which base on Northwind database. Please help me to how to get total rows without query again.
CREATE PROCEDURE [dbo].[SearchEmployees]
#search nvarchar(4000)
,#orderBy varchar(200)
,#PageSize int
,#PageIndex int
,#TotalRowsNumber int output
AS
DECLARE #PageLowerBound int
DECLARE #PageUpperBound int
SET #PageLowerBound = #PageSize * #PageIndex
SET #PageUpperBound = #PageSize + #PageLowerBound
--Default order by to first column
IF (#OrderBy is null or LEN(#OrderBy) < 1)
BEGIN
SET #OrderBy = 'EmployeeID DESC'
END
-- SQL Server 2005 Paging
declare #SQL as nvarchar(4000)
declare #SQLCOUNT as nvarchar(4000)
declare #Param as nvarchar(500)
SET #SQL = 'WITH PageIndex AS ('
SET #SQL = #SQL + ' SELECT '
IF #PageSize > 0
BEGIN
SET #SQL = #SQL + ' TOP ' + convert(nvarchar, #PageUpperBound)
END
SET #SQL = #SQL + ' ROW_NUMBER() OVER (ORDER BY ' + #OrderBy + ') as RowIndex '
SET #SQL = #SQL + ' ,EmployeeID'
SET #SQL = #SQL + ', LastName'
SET #SQL = #SQL + ', FirstName'
SET #SQL = #SQL + ', Title'
SET #SQL = #SQL + ' FROM employees'
IF Len(#Search) > 0
BEGIN
SET #SQL = #SQL + ' ' + #Search
END
SET #SQL = #SQL + ') SELECT '
SET #SQL = #SQL + ' EmployeeID'
SET #SQL = #SQL + ', LastName'
SET #SQL = #SQL + ', FirstName'
SET #SQL = #SQL + ', Title'
SET #SQL = #SQL + ' FROM PageIndex '
SET #SQL = #SQL + ' WHERE RowIndex > ' + convert(nvarchar, #PageLowerBound)
IF #PageSize > 0
BEGIN
SET #SQL = #SQL + ' AND RowIndex <= ' + convert(nvarchar, #PageUpperBound)
END
--Get Row Count
SET #SQLCOUNT = 'SELECT #TotalRowsNumber = count(EmployeeID)
FROM employees'
SET #Param = N'#Search nvarchar(2000),#TotalRowsNumber INT OUTPUT'
IF LEN(#Search) > 0
BEGIN
SET #SQLCOUNT = #SQLCOUNT + #Search
END
exec sp_executesql #SQL
exec sp_executesql #SQLCOUNT, #Param,#Search=#Search,#TotalRowsNumber = #TotalRowsNumber OUT
Thanks in advance!
Try Like this, See it as an example
CREATE Procedure usp_GetBookings
#pageIndex int,
#pageSize tinyint
as
;with CTE as
(
Select Distinct ROW_NUMBER() over( order by ssi.SSItineraryID desc) as seq ,Count(*) over() as TotalRow,ssi.SSItineraryID
from SightSeeingItinerary as ssi
)
select * from CTE
where cte.seq between (#pageIndex-1) * #pageSize+1 and ((#pageIndex-1) * #pageSize +(#pageSize))
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.