EXIST SQL Simplify - sql

-- Insert statements for procedure here
IF EXISTS
(SELECT S.SCHEDULER_ID FROM Scheduler S WITH (NOLOCK)
INNER JOIN CaseDetails_Scheduler_Mapping CDSM WITH (NOLOCK) ON (S.SCHEDULER_ID=CDSM.SCHEDULER_ID)
INNER JOIN CaseDetails CD WITH (NOLOCK) ON (CDSM.CASE_DETAIL_ID = CD.CASE_DETAIL_ID)
WHERE S.HEARD_BEFORE_ID=#HEARD_BEFORE_ID AND S.SCHEDULE_START_TIME=#SCHEDULE_START_TIME AND S.SCHEDULE_DATE=#SCHEDULE_DATE)
BEGIN
SELECT '4' AS 'STATUS', (SELECT S.SCHEDULER_ID FROM Scheduler S WITH (NOLOCK)
INNER JOIN CaseDetails_Scheduler_Mapping CDSM WITH (NOLOCK) ON (S.SCHEDULER_ID=CDSM.SCHEDULER_ID)
INNER JOIN CaseDetails CD WITH (NOLOCK) ON (CDSM.CASE_DETAIL_ID = CD.CASE_DETAIL_ID)
WHERE S.HEARD_BEFORE_ID=#HEARD_BEFORE_ID AND S.SCHEDULE_START_TIME=#SCHEDULE_START_TIME AND S.SCHEDULE_DATE=#SCHEDULE_DATE) AS 'SCHEDULER_ID',
(SELECT CD.CASE_NO FROM Scheduler S WITH (NOLOCK)
INNER JOIN CaseDetails_Scheduler_Mapping CDSM WITH (NOLOCK) ON (S.SCHEDULER_ID=CDSM.SCHEDULER_ID)
INNER JOIN CaseDetails CD WITH (NOLOCK) ON (CDSM.CASE_DETAIL_ID = CD.CASE_DETAIL_ID)
WHERE S.HEARD_BEFORE_ID=#HEARD_BEFORE_ID AND S.SCHEDULE_START_TIME=#SCHEDULE_START_TIME AND S.SCHEDULE_DATE=#SCHEDULE_DATE) AS 'CASE_NO'
END
I know this code are correct , but is there a way to simplify my sql code? i try did select 2 column in 1 table but it will appear "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error..... Sorry if i asking such beginner question..

I think you can remove the IF EXISTS part. Here is a simplified version of your THEN part:
SELECT
'4' AS [STATUS],
S.SCHEDULER_ID AS [SCHEDULER_ID],
CD.CASE_NO AS [CASE_NO]
FROM Scheduler S WITH (NOLOCK)
INNER JOIN CaseDetails_Scheduler_Mapping CDSM WITH (NOLOCK)
ON (S.SCHEDULER_ID = CDSM.SCHEDULER_ID)
INNER JOIN CaseDetails CD WITH (NOLOCK)
ON (CDSM.CASE_DETAIL_ID = CD.CASE_DETAIL_ID)
WHERE
S.HEARD_BEFORE_ID = #HEARD_BEFORE_ID
AND S.SCHEDULE_START_TIME = #SCHEDULE_START_TIME
AND S.SCHEDULE_DATE = #SCHEDULE_DATE
Note that putting NOLOCK everywhere is considered a bad habit.

Related

Convert fractions into decimal in sql using a function and select statements

Every time I try to run the following in Microsoft SQL Server Management Studio, I get an error message
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations
Is there anyway at all to run this in one statement?
The reason why I'm calling a function in this statement (dbo.ufn_ConvertJambDepthFractionToNumber) is because the dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue AS [Jamb Depth] column spits out values like 4 1/6", 3 1/4", 6 9/16". I'm using that function to try to convert the varchar values (4 1/6", 3 1/4", 6 9/16") into decimals.
If there is a better way to do that, I'm all ears.
use BeechworthProdWTS
declare #jamb_depth as varchar
SELECT DISTINCT
dbo.QuoteShippingAddress.Name AS [CDS Location],
dbo.QuoteShippingAddress.Address1 AS [Quote Shipping Address1],
dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue AS [Jamb Depth],
dbo.CDS_Shipments_Door_Count_view.Doors,
dbo.CDS_Shipments_Screen_Count_view.Screens,
dbo.CDS_Shipments_Windows_Count_view.Windows,
dbo.LineItemMaster.LineNumber,
#jamb_depth = dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue,
dbo.ufn_ConvertJambDepthFractionToNumber(#jamb_depth)
FROM
dbo.Quotes
INNER JOIN
dbo.QuoteShippingAddress WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.QuoteShippingAddress.QuoteID
INNER JOIN
dbo.Clients WITH (NOLOCK) ON dbo.Quotes.ClientID = dbo.Clients.ClientID
INNER JOIN
dbo.CustomerProjectInformation WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.CustomerProjectInformation.QuoteID
INNER JOIN
dbo.LineItemMaster WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.LineItemMaster.QuoteID
INNER JOIN
dbo.LineItems WITH (NOLOCK) ON dbo.LineItemMaster.LineItemMasterID = dbo.LineItems.LineItemMasterID
INNER JOIN
dbo.WorkOrders WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.WorkOrders.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Door_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Door_Count_view.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Door_Overall_Jamb_Depth WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Door_Overall_Jamb_Depth.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Screen_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Screen_Count_view.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Windows_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Windows_Count_view.LineItemID
Since you say you are pretty new to SQL I reformatted this using aliases so you can see how much difference it make visually. This doesn't affect performance but it does keep the developer sane. Also, not really sure what you are trying to do with your scalar but maybe trying to get the value for each row?
Cleaned up your query might look something like this.
SELECT DISTINCT
qsa.Name AS [CDS Location],
qsa.Address1 AS [Quote Shipping Address1],
sdojd.InstructionValue AS [Jamb Depth],
sdcv.Doors,
sscv.Screens,
swcv.Windows,
lim.LineNumber,
--#jamb_depth = sdojd.InstructionValue, --not really sure what you are trying to do here
--dbo.ufn_ConvertJambDepthFractionToNumber(#jamb_depth)
JambDepth = dbo.ufn_ConvertJambDepthFractionToNumber(sdojd.InstructionValue)
FROM dbo.Quotes q
INNER JOIN dbo.QuoteShippingAddress qsa ON q.QuoteID = qsa.QuoteID
INNER JOIN dbo.Clients c ON q.ClientID = c.ClientID
INNER JOIN dbo.CustomerProjectInformation cpi ON q.QuoteID = cpi.QuoteID
INNER JOIN dbo.LineItemMaster lim ON q.QuoteID = lim.QuoteID
INNER JOIN dbo.LineItems li ON lim.LineItemMasterID = li.LineItemMasterID
INNER JOIN dbo.WorkOrders wo ON li.LineItemID = wo.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Door_Count_view sdcv ON li.LineItemID = sdcv.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Door_Overall_Jamb_Depth sdojd ON li.LineItemID = sdojd.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Screen_Count_view sscv ON li.LineItemID = sscv.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Windows_Count_view swcv ON li.LineItemID = swcv.LineItemID

Need assistance with T-SQL query UNION, JOINS, COUNT

Looks that I am stumped with query to sum up shipments grouped by by union operator. Today I was working to retrieve total shipments (count(Distinct. U.SjipmentId) delivered by agent, driver (U.AgentCode) to particular country (U.CtryCode, U.CtryName). The last thing I would like to do is to sum all the shipments together to get the total amount of shipments.
Would anyone advise how I this can be achieved in easy and simply way?
Below you can find my most current query.
SELECT U.AgentCode, U.CtryCode, U.CtryName, count(distinct U.Id)
FROM (
select Agent.AgentCode, Addr.CtryCode, Ctry.Name, Ship.Id
from Shipment
LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.ID
LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = RouteTbl.AgentID
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTbl.Bur ='GB01' AND Agent.AgentCode IS NOT NULL
Union ALL
select Driver.DriverCode, Addr.CtryCode, Ctry.Name, Shipment.Id
from Shipment
LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.Id
LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = RouteTbl.DriverId
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTbl.Bur ='GB01' AND Driver.DriverCode IS NOT NULL
) as U
GROUP BY U.AgentCode, U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName
Union statements need to have the exact same column names, in your code below the Union All command, try this:
select Driver.DriverCode as AgentCode, Addr.CtryCode, Ctry.Name, Shipment.Id
Also change the Ctry.Name to Ctry.Name as CtryName in both your select statements.
You have the same code from your UNION. Good way to use WITH clause.
In your select you don't need a UNION - use a left join and COALESCE instead.
;With r_tab AS
(
select RouteTab.AgentID, Addr.CtryCode, Ctry.Name, Ship.Id,RouteTab.DriverId
from Shipment
LEFT JOIN RouteTab (nolock) ON RouteTab.Cexp= Shipment.ID
LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
WHERE RouteTab.Bur ='GB01'
)
SELECT COALESCE(Agent.AgentCode,Driver.DriverCode) AgentCode, U.AgentCode, U.CtryCode, U.CtryName,
count(distinct U.Id)
FROM r_tab U
LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = U.AgentID
AND Agent.AgentCode IS NOT NULL
LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = U.DriverId
AND Driver.DriverCode IS NOT NULL
GROUP BY COALESCE(Agent.AgentCode,Driver.DriverCode), U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName`enter code here`

How do I use a table name that's returned in a select statement, in a join?

*Note: This is not the same as the "possible duplicate". Here, the table name will be different for each record returned in the SELECT statement. So I can't just "set" a variable like set #tableName = 'whatever'.
Here's my SQL - take a look at my last inner join. e.Name from the table EmailSendDefintion is the name of the table I need to join to. So, this is kind of dynamic, I know, but how do I join to a table that is stored in a field in another table?
select top 5000
x.HL_ACCT_ID as 'HL_ACCT_ID',
x.SALE_CODE as 'SALE_CODE',
s.SubscriberKey as 'EmailAddress',
o.EventDate as 'Opened',
c.EventDate as 'Clicked',
b.EventDate as 'Bounced'
from c100._sent s with (nolock)
inner join c100._job j with (nolock) on s.jobid = j.jobid
inner join emailsenddefinition e with (nolock) on e.customerkey = j.emailsenddefinition
left join c100._open o with (nolock) on o.jobid = s.jobid and o.subscriberkey = s.subscriberkey
left join c100._click c with (nolock) on c.jobid = s.jobid and c.subscriberkey = s.subscriberkey
left join c100._bounce b with (nolock) on b.jobid = s.jobid and b.subscriberkey = s.subscriberkey
inner join c100.[e.name] x with (nolock) on x.EmailAddress = s.SubscriberKey
where e.clientid = 100
Perhaps you could just create a view that outputs the union of all the e.name tables? Then join to the view.
In order to keep this short, let's say you have just 2 different tables whose name could be in the e.name column, SubscriberEmail1 and SubscriberEmail2.
Then you could create a view like this:
CREATE VIEW SubscriberEmailUnion
AS
SELECT
'SubscriberEmail1' as TableName,
HL_ACCT_ID,
SALE_CODE,
EmailAddress
FROM SubscriberEmail1
UNION
SELECT
'SubscriberEmail2' as TableName,
HL_ACCT_ID,
SALE_CODE,
EmailAddress
FROM SubscriberEmail2
GO
Note that each part of the view is adding the name of it's underlying table as a column. You can then change your final join to:
inner join SubscriberEmailUnion x with (nolock) on (
x.EmailAddress = s.SubscriberKey
AND x.TableName = e.Name
)
I'm personally most familiar with MS Sql Server so my sample uses that syntax. Should be easy enough to change to work with a different server if necessary though.
For performance you can then use whatever feature your DB has, indexed views etc.
How many tables do you have? If not too many one option would be to left join all of them
left join c100.table1 x1 on x1.EmailAddress = s.SubscriberKey and [e.name] = 'table1'
left join c100.table2 x1 on x2.EmailAddress = s.SubscriberKey and [e.name] = 'table2'
etc...
and then in the select
coalesce(x1.HL_ACCT_ID, x2.HL_ACCT_ID, etc...) as 'HL_ACCT_ID',

Join on a comma-deli string column - sql server

I have a code in the stored procedure and it needs to join on a comma-deli string column. I tried but it is failing to recognized by sql server. Please let me know the right approach for it. Here is the code from the sproc:
INSERT INTO CPE_EXT_Downloaded (FileName, LocalServerID, WaitingACK, CreationDate, FileSize, MD5, ErrorMsgTime, LocationID, OfferID)
SELECT
cip.FileName, LS.LocalServerID, cip.WaitingACK, cip.CreationDate,
cip.FileSize, cip.MD5, cip.ErrorMsgTime, ILV.LocationID, cip.OfferID
FROM
#WorkSet ws
INNER JOIN
CPE_IncentiveDLBuffer_Pending cip WITH (NOLOCK) ON cip.POID = ws.POID
INNER JOIN
CPE_IncentiveLocationsView AS ILV WITH (NOLOCK) ON ILV.IncentiveID = cip.OfferID
INNER JOIN
LocalServers AS LS WITH (NOLOCK) ON LS.LocationID = ILV.LocationID
CROSS APPLY on
dbo.split(cip.LocationGroups, ',') AS ST ON st.items = ILV.LocationID
WHERE
LS.MustIPL = 0
Have you considered doing a regular join instead?
FROM #WorkSet ws
INNER JOIN CPE_IncentiveDLBuffer_Pending cip WITH (NOLOCK)
on cip.POID = ws.POID
inner join CPE_IncentiveLocationsView as ILV WITH (NOLOCK)
on ILV.IncentiveID= cip.OfferID and
','+cip.LocationGroups+',' like '%,'+ILV.LocationId+',%'
Inner Join LocalServers as LS with (NoLock) on LS.LocationID=ILV.LocationID

LEFT JOINS in MS Access

I am trying to troubleshoot someone else's MS Access query and keep getting an invalid operation error. The Help doesn't seem to apply as I am just running a query. It all works as INNER JOINS but when I switch back to the LEFT JOIN the error.
SELECT *
FROM ((((orders
INNER JOIN orders_customers ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number)
INNER JOIN lines_qry ON orders.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID
I can get one level of LEFT JOIN, but each time I add a second LEFT JOIN the error pops up.
Access' db engine frequently balks when mixing INNER and LEFT joins. If that query works without the last inner join ...
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
... then you could try that part as a subquery and inner join lines_qry to the subquery. It might get past the error.
SELECT *
FROM
(
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
) AS sub
INNER JOIN lines_qry
ON sub.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID
If any other table besides orders includes a field named CUST_ORDER_ID, you will need something other than SELECT * within the subquery to avoid ambiguity.
SELECT *
FROM
(
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
) AS sub
INNER JOIN lines_qry
ON sub.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID