how to execute procedure with multiply arguement? - sql

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'

Related

Stored procedure VS query output

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)

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

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.

T-SQL Dynamic variable insert

can some one help, with this query. I have 10 rows in my temp table
Declare #date date = '2014-11-01'
Declare #iDate int = '20141101'
Create table #test33(Paname varchar(100))
insert into #test33
Go
Now i have 10 rows in temp table. I want to insert those temp values in my cte dynamically
Declare #StartDate date = '2014-11-01'
Declare #EndDate date = '2014-11-30'
Declare #Paname nvarchar(100) = 'MPU' --- i have multiple panames how can i insert dyamically in cte or any other solution?
;with pla as
( SELECT*
FROM [dbo].[Pla] pl
JOIN dbo.testplan cl
ON pl.ClientId = cl.ClientId
where pl.name = #Paname
and pl.StartDate >= #StartDate and pl.EndDate <= #EndDate
)
select * from pla
You can loop throw multiple parameters using WHILE or using CURSOR. Inside it you can used dynamic sql:
declare #DSQL varchar(MAX)
SET #DSQL = ';with pla as
( SELECT*
FROM [dbo].[Pla] pl
JOIN dbo.testplan cl
ON pl.ClientId = cl.ClientId
where pl.name = '+#Paname+'
and pl.StartDate >= '+#StartDate+' and pl.EndDate <= '+#EndDate+'
)
select * from pla'
EXEC(#DSQL)

Writing a Stored Procedure If/Else to create error message

I am trying to create a stored procedure with an if/else statement that will result in a Text message if the wrong CustomerID is entered into the stored procedure. As it is now it will only give me a print line when there is nothing entered in the CustomeID.
Create proc spCustOrder
#CustomerID VarChar(10),
#StartDate SmallDateTime = null,
#EndDate SmallDateTime = NUll
as
Begin
iF #CustomerID > 0
Select Distinct OrderID, OrderDate
from Customer C join CustOrder CO on CO.CustomerID = C.CustomerID
where C.CustomerID = #CustomerID and
OrderDate >= Isnull(#startDate,'1900-01-01') and
OrderDate <= IsNull(#EndDate, getDate( ))
Else
Print 'Please enter a CustomerID'
end
Basically what i am unclear on is what should i use instead of the "0" in this "#CustomerID > 0" to make the program function. i tried using CustomerID or C. and CO.CustomerID but it says that there is an error with using that command.
Try
IF Exists(
SELECT DISTINCT OrderID, ...
)
ELSE
PRINT ...
END
Also, you typically want to return an ID or true/false value from stored procedures and do any printing or IO in the routine that calls the proc; avoid doing IO in the proc itself.
Your query as written doesn't seem to require the Customers table, so the query can be written as:
Select OrderID, OrderDate
from CustOrder CO
where CO.CustomerID = #CustomerID and
OrderDate >= Isnull(#startDate,'1900-01-01') and
OrderDate <= IsNull(#EndDate, getDate( ));
You then want to print something when there are no rows in the table. I would suggest using a temporary table for storing the intermediate results so they don't have to be calculated twice. The result is something like this:
Create procedure spCustOrder (
#CustomerID VarChar(10),
#StartDate SmallDateTime = null,
#EndDate SmallDateTime = NUll
)
as Begin
Select OrderID, OrderDate
into #tmp
from CustOrder CO
where CO.CustomerID = #CustomerID and
OrderDate >= Isnull(#startDate,'1900-01-01') and
OrderDate <= IsNull(#EndDate, getDate( ));
if exists (select 1 from #tmp)
begin
select *
from #tmp;
end
else
Print 'Please enter a CustomerID'
end; -- spCustOrder
I have used SQL Server's RAISERROR function to throw an error if user doesnt pass a CustomerID.
RETURN keyword will stop the code execution there and exit, no further lines of code will be executed after the RETURN keyword. i.e if the value for #CustomerID is null or 0 and control enters the IF Block.
Create proc spCustOrder
#CustomerID VarChar(10) = NULL,
#StartDate SmallDateTime = null,
#EndDate SmallDateTime = NUll
AS
BEGIN
SET NOCOUNT ON;
IF (#CustomerID IS NULL OR #CustomerID = 0)
BEGIN
RAISERROR('Please enter a CustomerID',16,1)
RETURN;
END
Select Distinct OrderID, OrderDate
from Customer C join CustOrder CO
on CO.CustomerID = C.CustomerID
where C.CustomerID = #CustomerID
and OrderDate >= Isnull(#startDate,'1900-01-01')
and OrderDate <= IsNull(#EndDate, getDate( ))
END
To be honest I would do it completely different. you can use code like:
ALTER PROCEDURE name
#CustomerID (uniqueidentifier) - varchar is very bad solution for your performance
#date1 DATE,
#date2 DATE,
#result INT OUTPUT=0 - use it as output parameter and handle text in app code
AS
BEGIN TRAN
IF EXISTS (your SELECT query. You don't need DISTINCT)
BEGIN
-- if exists do something smart. I don't know... UPDATE TABLE
IF ##error<>0
BEGIN
SET #result=1 --there was an error executing query in something smart
END
ELSE - from IF EXISTS statement
BEGIN
SET #result=2 --means no records found
END
IF #result=1
BEGIN
RETURN 1 --you know that this is error from your application code
ROLLBACK TRAN --there was an error in doing something smart
END
IF #result=2
RETURN 2 -- from your application code you know that this means no users found
END
IF RETURN=0
BEGIN
RETURN 0 -- userid found and something smart done without error :)
COMMIT TRAN
END
Hope this helps. You should analyze more bit about what will you do on application level and what do you want to do on DB level.
If helped mark it if no, ping with questions
Try IS NULL :
Create proc spCustOrder
#CustomerID VarChar(10),
#StartDate SmallDateTime = null,
#EndDate SmallDateTime = NUll
as
Begin
iF (#CustomerID IS NULL)
Select Distinct OrderID, OrderDate
from Customer C join CustOrder CO on CO.CustomerID = C.CustomerID
where C.CustomerID = #CustomerID and
OrderDate >= Isnull(#startDate,'1900-01-01') and
OrderDate <= IsNull(#EndDate, getDate( ))
Else
Print 'Please enter a CustomerID'
end