Stored procedure VS query output - sql

I try this SQL query
select
count(tblVV.PName) as total,
tblVV.PName
from
tblVV
inner join
tblRV on tblVV.MID = tblRV.ID
inner join
tblReg on tblRV.RID = tblReg.RID
where
tblReg.StartDate>= '2016-07-01 00:00:00' and
tblReg.EndDate<= '2016-07-31 23:59:59' and
tblReg.Region = 'uk' and
tblRegionVehicles_Uni.RegNo = 'BE82' and
tblVV.PName <>''
group by
tblVV.PName
This shows result like this
total PName
1 Sugar
11 Apple
Now when I create a stored procedure of same query like this
create procedure sp_ownerdata
#fromdate datetime,
#todate datetime,
#region varchar,
#RegNo varchar
as
select
count(tblVV.PName) as total,
tblVV.PName
from
tblVV
inner join
tblRV on tblVV.MID = tblRV.ID
inner join
tblReg on tblRV.RID = tblReg.RID
where
tblReg.StartDate >= #fromdate and
tblReg.EndDate <= #todate and
tblReg.Region = #region and
tblRegionVehicles_Uni.RegNo = #RegNo and
tblVV.PName <>''
group by
tblVV.PName
and execute like this
execute sp_ownerdata '2016-07-01 00:00:00','2016-07-31 23:59:59','uk','BE82'
then this shows nothing where as I write correct parameters name and correct values I enter when I execute the stored procedure
total PName

Problem in parameters length
#region varchar,
#RegNo varchar
You need to specify proper length for VARCHAR parameters in stored procedure
#region varchar(10),
#RegNo varchar(10)

Related

how to execute procedure with multiply arguement?

create proc [dbo].[SSRproc] (
#StartDate Date
,#EndDate Date
,#DepartmentGroupKey int
)
as begin
select F.Date,
F.AccountKey,
F.Amount,
F.OrganizationKey,
O.OrganizationName,
F.DepartmentGroupKey,
D.DepartmentGroupName
from [AdventureWorksDW2017].[dbo].[FactFinance] as f
inner join dbo.DimOrganization as O on F.OrganizationKey = O.OrganizationKey
inner join dbo.DimDepartmentGroup as D on F.DepartmentGroupKey = D.DepartmentGroupKey
where F.Date between #StartDate and #EndDate and #DepartmentGroupKey = F.DepartmentGroupKey
end
[dbo].[SSRproc] '2010-12-29', '2011-01-29', (3,5)
here is my procedure code and at the end I have execution but I need DepartmentGroupKey has multiply argument like key will be (3,5) or (3,8,9) and like that what I have to do?
If your Procedure is called from where a Table Valued Parameter is supported that would be the best solution. But if your Procedure is called from somewhere else this is not always possible so here is a alternative.
create proc [dbo].[SSRproc] (
#StartDate Date
,#EndDate Date
,#DepartmentGroupKey varchar(10)
)
as begin .....
.....and F.DepartmentGroupKey in (select value from STRING_SPLIT(#DepartmentGroupKey)
And then the execute:
execute dbo.SSRproc
#DepartmentGroupKey = '3,5'

Add multi value to a parameter in sql but my code not work [i'm newbie]

Add multi value to a parameter in sql but this query result is null table, can you help me !
Start code
CREATE Proc [dbo].[USP_LoadCustomerReportWithMultiCategory]
#companyID int , #arrivalDate datetime , #departureDate datetime , #productCategoryID varchar (100)
AS
BEGIN
Select
Company.CompanyName,
Customer.CustomerName,
Customer.ArrivalDate,
SUM((CustomerInfo.ProductQuantity * Product.ProductPriceSell)) as Total
From
CustomerInfo , Customer , Product,Company,ProductCategory
where
CustomerInfo.CustomerID = Customer.CustomerID and
Product.ProductID = CustomerInfo.ProductID and
Product.ProductCategoryID = ProductCategory.ProductCategoryID and
Company.CompanyID = Customer.CompanyID and
Customer.CompanyID = #companyID and
Customer.ArrivalDate between #arrivalDate and #departureDate and
CAST(Product.ProductCategoryID AS VARCHAR) in (#productCategoryID)
Group By
Customer.CustomerName,
Company.CompanyName,
Customer.ArrivalDate,
END
GO
End code
You are missing some fields in Group By:
ProductQuantity
ProductPriceSell
CustomerID
ProductID
ProductCategoryID
CompanyID
Please add those into the Group By section.

SQL where clause not getting filtered

I have the following query, but it is not giving any regard to the in the p.created_by =#searchBy where clause, how to correct it so that the results would be filtered according #searchBy too.
ALTER PROC [dbo].[Rptcashcollectionouter] #branchId INT,
#searchBy INT,
#strDate DATETIME=NULL,
#endDate DATETIME=NULL
AS
BEGIN
SELECT DISTINCT p.created_on AS paid_date
FROM reading re
JOIN billing_gen bg ON re.id = bg.reading_id
JOIN customer_registration cr ON bg.account_number = cr.account_number
JOIN payment p ON bg.bill_number = p.bill_number
JOIN customer_category cc ON cr.customer_category_id = cc.id
WHERE p.created_by = #searchBy
AND ( ( #strDate IS NULL )
OR Cast(Floor(Cast(p.created_on AS FLOAT)) AS DATETIME) >=
Cast(Floor(Cast(#strDate AS FLOAT)) AS DATETIME) )
AND ( ( #endDate IS NULL )
OR Cast(Floor(Cast(p.created_on AS FLOAT)) AS DATETIME) <=
Cast(Floor(Cast(#endDate AS FLOAT)) AS DATETIME) )
AND cr.branch_id = #branchId
ORDER BY p.created_on ASC;
END;
Check the value inside your procedure as below.
SELECT #branchId, #searchBy, #strDate,#endDate
And, then try to run the SQL manually with the same value. Also, make sure you have data in your table for your criteria.
Also, what exactly you are trying here ?
Cast(Floor(Cast(p.created_on AS FLOAT)) AS DATETIME)
While executing procedure, make sure you are passing properly value.
Print out all values that are coming (Just for testing).
#searchBy INT is of integer type. But i think "p.created_by =#searchBy" is a type of datetime or date , so it may also conflicts here, or display wrong result. In below line. p.created_by is treating as a datetime or date and #searchby in integer.
WHERE p.created_by = #searchBy

suddenly query executing slowly

I have very typical situation where I'm doing wrong. I have query which have executed fast initially but later on it taking loads of time to execute ..
My query :
Declare
#fromdate varchar(20) = '01/01/2014',
#todate varchar(20)= '27/05/2015',
#SERVICE_ID CHAR(5) = '123'
DECLARE #FDATE DATETIME ,
#TDATE DATETIME
SET #FDATE = (CONVERT(DATETIME,#fromdate,103))
SET #TDATE = (CONVERT(DATETIME,#todate,103))
IF OBJECT_ID('tempdb..#RUID') IS NOT NULL
DROP TABLE #RUID
CREATE TABLE #RUID(
OFFICEID INT,
OFFICE_TITTLE INT,
MAIN_OFFICE_TITTLE VARCHAR(50),
RLB_NAME VARCHAR(20),
DIST_NAME INT,
district_description VARCHAR(30))
CREATE CLUSTERED INDEX IDX_C_RUID_ID ON #RUID(OFFICEID)
CREATE NONCLUSTERED INDEX IDX_RUID_Name ON #RUID(OFFICE_TITTLE,DIST_NAME)INCLUDE(district_description)
INSERT INTO #RUID
SELECT OFFICEID,
OFFICE_TITTLE,
MAIN_OFFICE_TITTLE,
RLB_NAME,
DIST_NAME,
D.district_description
FROM APSDC..DISTRICT D
INNER JOIN cdma..Unified_RUID_WARD_MSTR I WITH(NOLOCK)
ON D.CDMA_DistrictID = I.DIST_NAME
WHERE RLB_NAME in(3) AND I.STATEID ='01'
select C.MAIN_OFFICE_TITTLE AS 'OFFICE_TITTLE',C.officeid, C.DIST_NAME AS DistrictName, C.district_description,
ISNULL(count(I.ApplicationNumber),0) 'Total_Trans',
isnull(sum(case when Data_Available='Y' AND DataTampered = 'N' then 1 else 0 end),0) 'CategoryA'
from #RUID c with(nolock)
LEFT JOIN Unified_BirthDeathAppDetails I WITH(NOLOCK) ON
(C.OFFICE_TITTLE=I.RUID AND C.DIST_NAME=I.DistrictName)
AND I.Service_Type= '01' AND
(DATEADD(DD,0,DATEDIFF(DD,0,I.Created_Date))) BETWEEN #FDATE AND #TDATE
AND NOT EXISTS(select application_number from reversal_details WITH(NOLOCK) WHERE ApplicationNumber <> i.ApplicationNumber AND service_id='123' )
group by C.MAIN_OFFICE_TITTLE,C.officeid, C.DIST_NAME,C.district_description
order by C.district_description ,C.MAIN_OFFICE_TITTLE
I have tried with #temp table and table variable but it is not even showing any result set. But the same query executed in 2 secs now it is taking lot of time. I have tried UPDATE Statstics on this tables and I have checked with locking also. What I need to do I have followed every other peformance optimized techinique.
Try:
Declare
#FDate Date = '01/01/2014',
#TDate Date= '27/05/2015',
#SERVICE_ID CHAR(5) = '123'
;WITH RUID
AS
(
SELECT OFFICEID,
OFFICE_TITTLE,
MAIN_OFFICE_TITTLE,
RLB_NAME,
DIST_NAME,
D.district_description
FROM APSDC..DISTRICT D
INNER JOIN cdma..Unified_RUID_WARD_MSTR I
ON D.CDMA_DistrictID = I.DIST_NAME
WHERE RLB_NAME in(3) AND I.STATEID ='01'
),
AppDetails
AS
(
SELECT ApplicationNumber,
CASE WHEN Data_Available='Y' AND DataTampered = 'N'
THEN 1
ELSE 0
END CategoryA
FROM Unified_BirthDeathAppDetails I
WHERE I.CreateDate >= #FDate AND I.CreatedDate < #TDate AND
NOT EXISTS
( select application_number
FROM reversal_details
WHERE I.Service_Type= '01' AND
ApplicationNumber <> i.ApplicationNumber AND
service_id= #Service_iD
)
)
SELECT C.MAIN_OFFICE_TITTLE AS OFFICE_TITTLE
,C.officeid, C.DIST_NAME AS DistrictName
, C.district_description
,ISNULL(count(I.ApplicationNumber),0) Total_Trans
,isnull(sum(CategoryA),0) CategoryA
FROM RUID c
LEFT JOIN AppDetails I
ON C.OFFICE_TITTLE=I.RUID AND C.DIST_NAME=I.DistrictName
GROUP BY C.MAIN_OFFICE_TITTLE
,C.officeid
,C.DIST_NAME
,C.district_description
ORDER BU C.district_description
,C.MAIN_OFFICE_TITTLE
Make sure you have decent indexes on RLB_name, StateId, CDMA_DistrictId, Dist_Name, CreatedDate etc.

SQL Return to front end

I have the following SQL Server stored procedure and when this is called by the front end code it returns the return value which is 0 instead of select of total count. can any one tell me what changes do i need to do to make it return the select values instead of return value
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getTotalSent1]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date
)
as
begin
select
camp.totalSent + bcamp.totalSent as totalSent
from
(select
COUNT(*) as totalSent
from
AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.CampaignID
from campaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)) as camp
join
(select
COUNT(*) as totalSent
from
AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select bc.BCampaignID
from BeaconCampaign bc, VendorWorkStation vw
where bc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)) as bcamp on 1=1
end
Output:
Totalsent
---------
240
return
-----
0
It's returning 0, I want total sent value
CREATE PROCEDURE getTotalSent1
AS
DECLARE #TotalSent int
-- Do some work here
SELECT #TotalSent = 240
RETURN #TotalSent
GO
-- EXEC CODE
DECLARE #totalsent int
EXEC #totalsent = dbo.getTotalSent1
SELECT #totalsent as totalSent
ALTER procedure [dbo].[getTotalSent1]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date
#total_set int output
)
as
`enter code here`
return
get param like this
declare #got_it int
exec [dbo].[getTotalSent1] xxx,yyy,#total_set=#got_it output
`
Try this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getTotalSent1]
(
#vendorworksationID uniqueidentifier ,
#sdate date,
#edate date
)
as
begin
DECLARE #totalSent INT
select
#totalSent =camp.totalSent + bcamp.totalSent
from
(select
COUNT(*) as totalSent
from
AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select cc.CampaignID
from campaign cc, VendorWorkStation vw
where cc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)) as camp
join
(select
COUNT(*) as totalSent
from
AdvertisedCampaignHistory a
where
CAST(a.CreationDate AS DATE) BETWEEN CAST(#sdate as DATE) AND CAST(#edate as DATE)
and a.CampaignID in (select bc.BCampaignID
from BeaconCampaign bc, VendorWorkStation vw
where bc.VendorWorkStationID = vw.VendorWorkStationID
and VendorID = #vendorworksationID)) as bcamp on 1=1
return #totalSent
end
After BEGIN type SET NOCOUNT ON;
This disables the default return value for stored procedures, so that you get the results of your query instead.
And as a side note, you need to replace your proprietary joins with the ANSI equivalent...
e.g.
...
FROM tblA a
JOIN tblB b
ON a.key = b.key
It's better to avoid doing the join in the WHERE clause.