I hope someone can help. I have created this stored procedure to pull some infromation from different tables and when i tun it I get many duplicates, I was wondering if there was a way of sorting it?
use ICA
if exists(
select *
from INFORMATION_SCHEMA.ROUTINES
where SPECIFIC_SCHEMA = N'ICASchema'
and SPECIFIC_NAME = N'candidateOffer'
)
drop procedure ICASchema.candidateOffer
go
create procedure ICASchema.candidateOffer #candidateID INT
as
begin
select c.CandidateID,c.CandidateName, ca.CourseID, co.CourseName, o.OfferID, ot.OfferTypePoints
from [ICASchema].[tblCandidate] c
join [ICASchema].[tblCandidateOffer] o on c.CandidateID = o.CandidateID
join [ICASchema].[tblOffer] ot on o.offerID = ot.OfferType
join [ICASchema].[tblCandidateApplication] ca on ca.CourseID = ca.CourseID
join [ICASchema].[tblCourse] co on co.CourseName = co.CourseName
where c.CandidateID = #candidateID
--ORDER BY co.CourseName
GROUP BY co.CourseName, c.CandidateID,c.CandidateName, ca.CourseID, o.OfferID, ot.OfferTypePoints
end
go
Thanks
Graham
Following example is for creating a simple Proc_GetAllUsers stored procedure. This will solve your duplication issue.
DROP PROCEDURE IF EXISTS Proc_GetAllUsers
GO
CREATE PROCEDURE Proc_GetAllUsers( )
BEGIN
-- your sql queries
select * FROM users;
END
Go
try this:
select * from (select distinct c.CandidateID,c.CandidateName, ca.CourseID, co.CourseName, o.OfferID, ot.OfferTypePoints
from [ICASchema].[tblCandidate] c
join [ICASchema].[tblCandidateOffer] o on c.CandidateID = o.CandidateID
join [ICASchema].[tblOffer] ot on o.offerID = ot.OfferType
join [ICASchema].[tblCandidateApplication] ca on ca.CourseID = ca.CourseID
join [ICASchema].[tblCourse] co on co.CourseName = co.CourseName
where c.CandidateID = #candidateID
GROUP BY co.CourseName, c.CandidateID,c.CandidateName, ca.CourseID, o.OfferID, ot.OfferTypePoints) tablealias order by CourseName
This was the working solution.
[code]SELECT c.CandidateID, c.CandidateName, ICASchema.tblOffer.OfferTypePoints, ICASchema.tblCourse.CourseName
FROM ICASchema.tblCandidate AS c INNER JOIN
ICASchema.tblCandidateOffer ON c.CandidateID = ICASchema.tblCandidateOffer.CandidateID INNER JOIN
ICASchema.tblOffer ON ICASchema.tblCandidateOffer.CandidateOfferID = ICASchema.tblOffer.OfferID INNER JOIN
ICASchema.tblCourse ON ICASchema.tblOffer.OfferID = ICASchema.tblCourse.OfferTypeID
WHERE (c.CandidateID = '3')
[/code]
Related
Can't find the same questions as mine I'm hoping you guys can help me.
I have this query for my SP what I need to do is check if the company Id is the same based on the parameter given by the user.
I have two parameters which are paramOrgA and paramOrgB which will be supplied by the user.
What I did was repeat the same query and set the returned value in two variables which is
orgAId and orgBId then use the IF statement to compare the value.
is there another way to accomplish this or should I say optimized way to do this?
Below is the query I wrote.
BEGIN
declare orgAId int;
declare orgBId int;
declare orgStatus bool;
SET orgAId = (SELECT c.Id
FROM Members as `m`
INNER JOIN Company as `c`
ON m.CompanyId = c.Id
WHERE m.Id = paramOrgA);
SET orgBId = (SELECT c.Id
FROM Members as `m`
INNER JOIN Company as `c`
ON m.CompanyId = c.Id
WHERE m.Id = paramOrgB);
IF (orgAId = orgBId) THEN
set orgStatus = true;
ELSE
set orgStatus = false;
END IF;
select orgStatus as 'CompanyStatus';
END IF;
END
One query will do
SELECT count(distinct c.Id) > 1 as 'CompanyStatus'
FROM Members as `m`
INNER JOIN Company as `c` ON m.CompanyId = c.Id
WHERE m.Id IN (paramOrgA, paramOrgB)
Even fewer keystrokes:
SELECT COUNT(DISTINCT CompanyId) > 1 as 'CompanyStatus'
FROM Members
WHERE Id IN (paramOrgA, paramOrgB)
We have a Web Api service for report building. This service uses MS SQL 2008 database as a data source. The data base works as a mirror in readonly mode.
The service and the database are hosted on different computers of a single local net.
There is a stored procedure in the database named TicketSaleByAggregator, that selects report data. Sometimes the procedure throws following exception:
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
Then the procedure is throwing this exception again and again until we recompile it:: ALTER PROCEDURE [dbo] [TicketSaleByAggregator].
After the command ALTER PROCEDURE, the procedure runs perfectly even on big data sets, but after about 10-15 hours the error throws again: Timeout expired
The procedure parameters:
DECLARE #PeriodFrom DATETIME = '2016-12-30 00:00:00'
DECLARE #PeriodTo DATETIME = '2016-12-30 23:59:59'
DECLARE #Dealers Identities
DECLARE #Branches Identities
DECLARE #SaleChannels Identities
DECLARE #Carriers Identities
INSERT INTO #Dealers (Id) VALUES(10068)
INSERT INTO #Branches(Id) VALUES(1),(2),(3)
INSERT INTO #SaleChannels(Id)VALUES (7)
exec TicketSaleByAggregator #PeriodFrom, #PeriodTo, #Dealers, #Branches, #SaleChannels, #Carriers
If we call the procedure locally (on the machine where it is hosted) in SQL Management Studio, then it executes for 15 seconds
If we call the procedure on the machine where the web api service is hosted, in SQL Management Studio, then it executes for 15-16 seconds
.The Result data contains 82540 records
Code of stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[TicketSaleByAggregator]
(
#PeriodFrom DATETIME,
#PeriodTo DATETIME,
#Dealers Identities READONLY,
#Branches Identities READONLY,
#SaleChannels Identities READONLY,
#Carriers Identities READONLY
)
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET NOCOUNT ON
;WITH ParentDealer(childId, parentId, BIN)
AS(
SELECT d.Id,
parentDealer.pId,
parentDealer.BIN
FROM Dealer AS d
JOIN (
SELECT d.Id,
parentDealer.Id pId,
parentDealer.BIN
FROM Dealer d
JOIN Dealer parentDealer
ON parentDealer.Hid = d.Hid.GetAncestor(d.[Hid].[GetLevel]() -1)
) parentDealer
ON d.Id = parentDealer.Id
),
CarrierNames
AS(
SELECT c.Name AS CarrierName
FROM Carrier AS c
INNER JOIN #Carriers crs ON c.Id = crs.Id
),
Result
AS(
SELECT *
FROM
(
SELECT t.[ExpressId] AS TicketExpressId,
o.[OrderCreateDate] AS OperationDate,
1 AS TicketCount,
t.[Tariff] AS Tariff,
6 AS OperationTypeId,
sc.Name AS SalesChannelName,
b.ShortName AS BranchName,
o.CarrierName,
o.PaymentType AS PaymentType,
--financial dealers
uDealer.Surname AS FinancialDealerSurname,
uDealer.Name AS FinancialDealerName,
uDealer.Middlename AS FinancialDealerPatronymic,
d.BIN AS FinancialDealerBin,
uparentDealer.Surname AS FinancialParentDealerSurname,
uparentDealer.Name AS FinancialParentDealerName,
uparentDealer.Middlename AS FinancialParentDealerPatronymic,
parentDealer.BIN AS FinancialParentDealerBin,
--place dealers
uDealer.Surname AS PlaceDealerSurname,
uDealer.Name AS PlaceDealerName,
uDealer.Middlename AS PlaceDealerPatronymic,
d.BIN AS PlaceDealerBin,
uparentDealer.Surname AS PlaceParentDealerSurname,
uparentDealer.Name AS PlaceParentDealerName,
uparentDealer.Middlename AS PlaceParentDealerPatronymic,
parentDealer.BIN AS PlaceParentDealerBin
FROM Ticket AS t
INNER JOIN [Order] AS o ON o.Id = t.OrderId AND o.OrderCreateDate BETWEEN #PeriodFrom AND #PeriodTo
INNER JOIN [Terminal] AS ter ON t.[TerminalId] = ter.[Id]
LEFT JOIN [TerminalData] AS td ON ter.[Id] = td.[Id]
INNER JOIN [SalePoint] AS sp ON td.[SalePointId] = sp.[Id]
INNER JOIN FinAccStation AS fas ON fas.Id = sp.FinAccStationId
INNER JOIN Guo AS g ON g.Id = fas.GuoId
INNER JOIN Department AS dep ON dep.Id = g.DepartmentId
INNER JOIN Dealer AS d ON d.Id = ter.DealerId
INNER JOIN [User] AS uDealer ON uDealer.Id = d.Id
INNER JOIN SalesChannel AS sc ON sc.Id = d.SalesChannelId AND (EXISTS(SELECT * FROM #SaleChannels) AND (d.SalesChannelId IN (SELECT * FROM #saleChannels)) OR NOT EXISTS(SELECT * FROM #saleChannels))
INNER JOIN Branch AS b ON b.Id = dep.BranchId AND (EXISTS(SELECT * FROM #Branches) AND (b.Id IN (SELECT * FROM #Branches)))
INNER JOIN ParentDealer AS parentDealer ON parentDealer.childId = d.Id AND (parentDealer.parentId IN (SELECT Id FROM #Dealers) OR NOT EXISTS(SELECT * FROM #Dealers))
INNER JOIN [User] AS uParentDealer ON uParentDealer.Id = parentDealer.parentId
WHERE t.TicketStatusId IN (3, 6) AND
((EXISTS(SELECT TOP 1 * FROM #Carriers) AND (o.CarrierName IN (SELECT CarrierName FROM CarrierNames))) OR NOT EXISTS(SELECT TOP 1 * FROM #Carriers))
UNION ALL
SELECT t.[ExpressId] AS TicketExpressId,
c.OperationDate AS OperationDate,
-1 AS TicketCount,
(-1)*ct.RetTariff AS Tariff,
3 AS OperationTypeId,
sc.Name AS SalesChannelName,
b.ShortName AS BranchName,
o.CarrierName,
c.PaymentType AS PaymentType,
--financial dealers
uDealer.Surname AS DealerSurname,
uDealer.Name AS DealerName,
uDealer.Middlename AS DealerPatronymic,
d.BIN AS DealerBin,
uparentDealer.Surname AS ParentDealerSurname,
uparentDealer.Name AS ParentDealerName,
uparentDealer.Middlename AS ParentDealerPatronymic,
parentDealer.BIN AS ParentDealerBin,
--place dealers
uDealer1.Surname AS PlaceDealerSurname,
uDealer1.Name AS PlaceDealerName,
uDealer1.Middlename AS PlaceDealerPatronymic,
d1.BIN AS PlaceDealerBin,
uparentDealer1.Surname AS PlaceParentDealerSurname,
uparentDealer1.Name AS PlaceParentDealerName,
uparentDealer1.Middlename AS PlaceParentDealerPatronymic,
parentDealer1.BIN AS PlaceParentDealerBin
FROM Cancelation AS c
INNER JOIN CancelationTicket AS ct ON ct.CancelationId = c.Id
INNER JOIN Ticket AS t ON t.Id = ct.TicketId
INNER JOIN [Order] AS o ON o.Id = c.OrderId
INNER JOIN Terminal AS ter ON ter.Id = IIF(o.PaymentType = 1, c.TerminalId, t.TerminalId)
INNER JOIN Terminal AS ter1 ON ter1.Id = c.TerminalId
LEFT JOIN [TerminalData] AS td ON td.[Id] = ter.Id
INNER JOIN [SalePoint] AS sp ON td.[SalePointId] = sp.[Id]
INNER JOIN FinAccStation AS fas ON fas.Id = sp.FinAccStationId
INNER JOIN Guo AS g ON g.Id = fas.GuoId
INNER JOIN Department AS dep ON dep.Id = g.DepartmentId
INNER JOIN Dealer AS d ON d.Id = ter.DealerId
INNER JOIN Dealer AS d1 ON d1.Id = ter1.DealerId
INNER JOIN [User] AS uDealer ON uDealer.Id = d.Id
INNER JOIN [User] AS uDealer1 ON uDealer1.Id = d1.Id
INNER JOIN SalesChannel AS sc ON sc.Id = d.SalesChannelId AND (EXISTS(SELECT * FROM #SaleChannels) AND (d.SalesChannelId IN (SELECT * FROM #saleChannels)) OR NOT EXISTS(SELECT * FROM #saleChannels))
INNER JOIN Branch AS b ON b.Id = dep.BranchId AND (EXISTS(SELECT * FROM #Branches) AND (b.Id IN (SELECT * FROM #Branches)))
INNER JOIN ParentDealer AS parentDealer ON parentDealer.childId = d.Id AND (parentDealer.parentId IN (SELECT Id FROM #Dealers) OR NOT EXISTS(SELECT * FROM #Dealers))
INNER JOIN [User] AS uParentDealer ON uParentDealer.Id = parentDealer.parentId
INNER JOIN ParentDealer AS parentDealer1 ON parentDealer1.childId = d1.Id
INNER JOIN [User] AS uParentDealer1 ON uParentDealer1.Id = parentDealer1.parentId
WHERE c.OperationDate BETWEEN #PeriodFrom AND #PeriodTo AND
((EXISTS(SELECT TOP 1 * FROM #Carriers) AND (o.CarrierName IN (SELECT CarrierName FROM CarrierNames))) OR NOT EXISTS(SELECT TOP 1 * FROM #Carriers)) AND
c.ResponseXml.value('(/GtETicket_Response/#Type)[1]','nvarchar(max)') != 'ExpressStatus'
)T
)
SELECT *
from Result
END
UPDATED: Code on C# side:
public IEnumerable<RegisterTicketsByDealerReportItem> GetRegisterTicketsByDealerReport(DateTime periodFrom, DateTime periodTo, int[] dealerIds, int[] salesChannelIds, int[] branchIds, int[] carrierIds)
{
var pars = new DynamicParameters();
var identityFailureValue = new { Id = 0 }.ToEmptyTable().AsTableValuedParameter("Identities");
pars.AddDynamicParams(
new
{
PeriodFrom = periodFrom,
PeriodTo = periodTo,
Dealers = dealerIds.Return(ds => ds.Select(d => new { Id = d }).ToDataTable().AsTableValuedParameter("Identities"), identityFailureValue),
Branches = branchIds.Return(br => br.Select(b => new { Id = b }).ToDataTable().AsTableValuedParameter("Identities"), identityFailureValue),
SaleChannels = salesChannelIds.Return(scs => scs.Select(sc => new { Id = sc }).ToDataTable().AsTableValuedParameter("Identities"), identityFailureValue),
Carriers = carrierIds.Return(scs => scs.Select(sc => new { Id = sc }).ToDataTable().AsTableValuedParameter("Identities"), identityFailureValue)
});
var result = Connection.Query<RegisterTicketsByDealerReportItem>("TicketSaleByAggregator", pars,
commandType: CommandType.StoredProcedure,
commandTimeout: dbConfiguration.SqlLargeTimeoutSeconds);
Connection.CloseIfNoTransaction();
return result;
}
Sql connection parametrs:
<add key="SqlLargeTimeoutSeconds" value="00:02:00" />
<add name="Readonly" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=db_Readonly;Integrated Security=True;" />
1- Try to use with(nolock) if it is non sensitive transnational data
2- Stop mirroring and check the speed. mirroring may cause this problem
I had to create many routines (stored procedures) for every query, how can I do the following procedures into one single procedure, same way I need to put around eight procedures like that, any idea could be helpful, thanks in advance.
Procedure 1
INSERT INTO public_holidays (user_id, department_id,designation_id,date_cur,clock_in,clock_out)
SELECT cl.user_id, des.department_id , us.designation_id, cl.date,cl.clock_in, cl.clock_out
FROM clock cl
INNER JOIN holidays AS hol ON hol.date = cl.date
INNER JOIN users AS us ON cl.user_id = us.id
INNER JOIN designations AS des ON des.id = us.designation_id
WHERE date(cl.created_at) = cur_dat
AND TIMESTAMPDIFF(second,cl.clock_in, cl.clock_out) = 28800;
Procedure 2
INSERT INTO public_holidays_nine (user_id, department_id,designation_id,date_cur,clock_in,clock_out)
SELECT clo.user_id, design.department_id , uses.designation_id, clo.date,clo.clock_in, clo.clock_out
FROM clock clo
INNER JOIN holidays AS holl ON holl.date = clo.date
INNER JOIN users AS uses ON clo.user_id = uses.id
INNER JOIN designations AS design ON design.id = uses.designation_id
WHERE date(clo.created_at) = cur_dat
AND TIMESTAMPDIFF(second,clo.clock_in, clo.clock_out) = 32400;
Try this
CREATE PROCEDURE `sp_test`(IN _date datetime)
BEGIN
#Routine body goes here...
INSERT INTO public_holidays (user_id, department_id,designation_id,date_cur,clock_in,clock_out)
SELECT cl.user_id, des.department_id , us.designation_id, cl.date,cl.clock_in, cl.clock_out
FROM clock cl
INNER JOIN holidays AS hol ON hol.date = cl.date
INNER JOIN users AS us ON cl.user_id = us.id
INNER JOIN designations AS des ON des.id = us.designation_id
WHERE date(cl.created_at) = cur_dat
AND TIMESTAMPDIFF(second,cl.clock_in, cl.clock_out) = 28800;
INSERT INTO public_holidays_nine (user_id, department_id,designation_id,date_cur,clock_in,clock_out)
SELECT clo.user_id, design.department_id , uses.designation_id, clo.date,clo.clock_in, clo.clock_out
FROM clock clo
INNER JOIN holidays AS holl ON holl.date = clo.date
INNER JOIN users AS uses ON clo.user_id = uses.id
INNER JOIN designations AS design ON design.id = uses.designation_id
WHERE date(clo.created_at) = cur_dat
AND TIMESTAMPDIFF(second,clo.clock_in, clo.clock_out) = 32400;
END
You can Call this Procedure as
CALL sp_test(param1)
I have a mysql query like...
SELECT OrderTransaction.buyer, OrderTransaction.parent_id
FROM order_transactions as OrderTransaction
INNER JOIN (
SELECT buyer
FROM order_transactions as dy
left join orders as ebay on ebay.id=dy.parent_id
where ebay.status='0' and dy.parent_id IN (
SELECT parent_id
FROM order_shipping_details as ds
left join orders as ebays on ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1
) and ebay.combined=0
group by dy.buyer
) dup ON dup.buyer=OrderTransaction.buyer
left join orders as ebay on ebay.id=OrderTransaction.parent_id
where ebay.market_type!='shopclue' and ebay.status='0' and ebay.combined=0
I need to optimize this query and want to remove the inner select with joins.
Any help would be appreciated. Thanks in advance.
Try this code below might be running faster than the one u currently using:
DROP TEMPORARY TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1;
SELECT buyer
FROM order_transactions AS dy
LEFT JOIN orders AS ebay ON ebay.id=dy.parent_id
WHERE ebay.status='0'
AND dy.parent_id
IN (
SELECT parent_id
FROM order_shipping_details AS ds
left join orders AS ebays ON ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1)
AND ebay.combined= '0'
;
SELECT
OrderTransaction.buyer,
OrderTransaction.parent_id
FROM order_transactions AS OrderTransaction
INNER JOIN temp1 AS tmp ON tmp.buyer = OrderTransaction.buyer
LEFT JOIN orders AS ebay ON ebay.id = OrderTransaction.parent_id
WHERE ebay.market_type! = 'shopclub' AND ebay.status = '0' and ebay.combined = '0'
Please let me know if you have any questions!
Hi I am looking for a query that is able to find Full text indexing on all tables and columns within a database using SQL Server 2008. Any information or help that can be provided for this is welcomed
Here's how you get them
SELECT
t.name AS ObjectName,
c.name AS FTCatalogName ,
i.name AS UniqueIdxName,
cl.name AS ColumnName
FROM
sys.objects t
INNER JOIN
sys.fulltext_indexes fi
ON
t.[object_id] = fi.[object_id]
INNER JOIN
sys.fulltext_index_columns ic
ON
ic.[object_id] = t.[object_id]
INNER JOIN
sys.columns cl
ON
ic.column_id = cl.column_id
AND ic.[object_id] = cl.[object_id]
INNER JOIN
sys.fulltext_catalogs c
ON
fi.fulltext_catalog_id = c.fulltext_catalog_id
INNER JOIN
sys.indexes i
ON
fi.unique_index_id = i.index_id
AND fi.[object_id] = i.[object_id];
select distinct
object_name(fic.[object_id])as table_name,
[name]
from
sys.fulltext_index_columns fic
inner join sys.columns c
on c.[object_id] = fic.[object_id]
and c.[column_id] = fic.[column_id]
I know this is an old thread, but I just now needed this answer, and found Sadra Abedinzadeh's answer above useful, but a slightly lacking for my needs, so I thought I'd post another answer here, which is a modification of Sadra's answer, to include Indexed Views with FullText Indexes, and some extra column information:
use MyDatabaseName -- Modify here, of course
SELECT
tblOrVw.[name] AS TableOrViewName,
tblOrVw.[type_desc] AS TypeDesc,
tblOrVw.[stoplist_id] AS StopListID,
c.name AS FTCatalogName ,
cl.name AS ColumnName,
i.name AS UniqueIdxName
FROM
(
SELECT TOP (1000)
idxs.[object_id],
idxs.[stoplist_id],
tbls.[name],
tbls.[type_desc]
FROM sys.fulltext_indexes idxs
INNER JOIN sys.tables tbls
on tbls.[object_id] = idxs.[object_id]
union all
SELECT TOP (1000)
idxs.[object_id],
idxs.[stoplist_id],
tbls.[name],
tbls.[type_desc]
FROM sys.fulltext_indexes idxs
INNER JOIN sys.views tbls -- 'tbls' reused here to mean 'views'
on tbls.[object_id] = idxs.[object_id]
) tblOrVw
INNER JOIN sys.fulltext_indexes fi
on tblOrVw.[object_id] = fi.[object_id]
INNER JOIN
sys.fulltext_index_columns ic
ON
ic.[object_id] = tblOrVw.[object_id]
INNER JOIN
sys.columns cl
ON
ic.column_id = cl.column_id
AND ic.[object_id] = cl.[object_id]
INNER JOIN
sys.fulltext_catalogs c
ON
fi.fulltext_catalog_id = c.fulltext_catalog_id
INNER JOIN
sys.indexes i
ON
fi.unique_index_id = i.index_id
AND fi.[object_id] = i.[object_id];