SQL Late Join With Case - Help...
Feb 6, 2006
All - I'm having some trouble, and I hope someone can give me some assistance. I've scoured Google, and have only found stuff similar to what I already have.
My company has an old commercial ERP package. The package has a table called 'Lot_Bin_Tran' that tracks movements of parts based on the part number and a 'Tran_code' - a one-character field that represents what kind of transaction it is (receipt, shipment, inventory adjustment, etc...). Using those two pieces of information, you can join this single table to any of the tables that hold the information (such as receipts). I tried to write a left join from my transaction table to my primary tables to look for transaction records that have no corresponding records in the primary tables. Some SQL might be helpful here...
Code:
SELECTLBT.*
FROMLOT_BIN_TRANLBT(NOLOCK),
PRODUCEP(NOLOCK),
ORDERSO(NOLOCK),
ISSUESI(NOLOCK),
RECEIPTSR(NOLOCK),
LOT_BIN_XFERLBX(NOLOCK)
WHERELBT.PART_NO = 'OUR_PART_NUMBER_GOES_HERE'
AND
LBT.TRAN_NO *=
CASE LBT.TRAN_CODE
WHEN 'I' THEN I.issue_no
WHEN 'P' THEN P.prod_no
WHEN 'R' THEN R.receipt_no
WHEN 'S' THEN O.order_no
WHEN 'T' THEN LBX.tran_NO
END
AND
((I.ISSUE_NO IS NULL) AND (P.PROD_NO IS NULL) AND (R.RECEIPT_NO IS NULL) AND (O.ORDER_NO IS NULL) AND (LBX.TRAN_NO IS NULL))
when I run this, though - I get the following message...
Quote:
Msg 301, Level 16, State 1
Query contains an illegal outer-join request.
If I change the Left join to an inner join (using = instead of *=), I get a resultset, but not the one I want (since I can't detect nulls in all tables using inner join). Any ideas on how I can restructure?
Thanks!
View 6 Replies
ADVERTISEMENT
Oct 11, 2013
IN SP i have the
AND EI.IID =TL.IID AND EI.GID=TL.GID
and TL.QID=EI.ID WHERE EI.TYPE='P'
but i need and TL.QID=EI.ID only when
@QID>0
if not > 0 the i dont need to add and TL.QID=EI.ID
i tried below
View 3 Replies
View Related
Oct 18, 2005
Is it possible to have a join with case statement in it?
i.e.
select * from a inner join b on
case [x] then a.xid = b.xid
case [y] then a.yid = b.yid?
View 3 Replies
View Related
Oct 16, 2007
Hi, I have two tables TABLE_A and TABLE_BTABLE_A has rows like this:PROJECT_IDTASK_ID TASK_NAME1 100 One Hundred1 110 One Hundred Ten1 120 One Hundred Twenty2 200 Two Hundred3 300 Three Hundred3 310 Three Hundred TenTABLE_B has rows like this:PROJECT_IDTASK_IDAMOUNT1 10010001 11011002 NULL20003 3003000I want to inner join TABLE_A and TABLE_B such that if TASK_ID is available in TABLE_B, then join should happen on TASK_ID (on TABLE_A.TASK_ID=TABLE_B.TASK_ID), if TASK_ID is not available the join should happen on PROJECT_ID.For example for PROJECT_ID=2, there is no TASK_ID in TABLE_B (in this situation the join should be ON PROJECT_ID)How can we do a CASE like situation here?Thanks in advanceqA
View 14 Replies
View Related
Mar 4, 2014
Is it possible to do something like this:
Select a.address from person p
join Addresses a on p.AddressPointer =
Case when @UseNewAddress=1 then a.NewAddress else a.OldAddress end
It gives a syntax error but I'm wondering if there's another way to do it.
View 2 Replies
View Related
Apr 24, 2007
Hi,
I have a 2 different telephone number tables,
Table 1 has some numbers beginning with '0' i.e. 08001234567 and some without the '0' i.e 8001234567
on my Table2 i only have numbers starting with '0' i.e 08001234567.
I would like to make a INNER JOIN statement and check if the telephone number dont have a starting '0', then append to it and try to do the join so I get both set of data.
for example (this doesnt work however...):
SELECT *
FROM dbo.Calls INNER JOIN
ON
CASE WHEN SUBSTRING(dbo.CallData.TelephoneNumber, 0, 1) = '0'
THEN dbo.Calls.TelephoneNumber = dbo.Post.TelephoneNumber
ELSE '0' & dbo.Calls.TelephoneNumber = dbo.Post.TelephoneNumber <--append a 0 at the start
END CASE
AND dbo.Products.FK_Client = dbo.CallDataSets.FK_Client
GROUP BY dbo.CallDataSets.FK_Client
I hope you understand what I am trying to achieve here...
Any help is appreciated!
Many thanks,
Jon
View 6 Replies
View Related
Sep 26, 2007
Hi All,
I am in need for to write the following query for a stored procedure in SQL Server 2000. Please observe the T-SQL code first.
Please disregard the numbers and Product Numbers, they are not the correct data. I used them for ease of understanding. But the query is identical.
Code Block
SELECT
C.iOwnerid,
MAX (C.DtInsertDate) AS [dtLastIssueDate]
INTO #Tble
FROM CustomerProduct C
CASE WHEN @vchSubscription = 'Weekly' THEN
INNER JOIN ProductMaster PM ON PM.chProductNumber = C.chProductNumber
AND ( ( PM.vchUser7='101557' AND PM.vchUser8='101557' ) -- Category and SubCategory
OR PM.chProductNumber IN (
'weekly1', 'Weekly2', 'Weekly3', 'Weekly4' )
)
AND C.dtInsertDate > = @dtIssueDate CASE WHEN @vchSubscription = 'Monthly' THEN
INNER JOIN ProductMaster PM ON PM.chProductNumber = C.chProductNumber
AND ( ( PM.vchUser7='101557' AND PM.vchUser8='101557' )
OR PM.chProductNumber IN (
'Jan', 'Feb', 'Mar', ....'Dec')
)
AND C.dtInsertDate > = @dtIssueDate
END
GROUP BY C.iOwnerid, PM.vchUser7, PM.vchUser8
my requirement is join the same table, but depending on the subscription type i have to join to different product numbers.
I hope you understand. I have been trying this since yesterday, but no luck.
Any help would be greatly appreciated.
View 4 Replies
View Related
Jan 29, 2015
I am trying to use this logic into a query:
Select P.S,E.S,E.R
from Pack P(nolock)
join Exp E on P.Id=E.O
on E.R is null
case when E.R is not null then ''
else ''
end
where P.s='PLT000044'
I have to query two conditions joining the tables. when E.R is NULL and when E.R is not null. but the value is coming from the join between the 2 tables :P and E.
View 2 Replies
View Related
Jun 22, 2006
I'm trying to join a table and based on the value of a given column I would join using the column in question, however if the column is NULL then I want to make the join without the column in the join. so I think I want to do something like this:
Case E.a
when NULL
then LEFT JOIN EPD ON EPD.b = D.b
AND EPD.SD = (SELECT MAX(E1.SD) FROM E1
WHERE E1.b = EPD.b AND E1.a = EPD.a AND E1.SD <= T.WD)
Else
LEFT JOIN EPD
ON EPD.a = D.a
and EPD.b = E.b
AND EPD.SD = (SELECT MAX(E1.SD) FROM E1
WHERE E1.a = EPD.a AND E1.b = EPD.b AND
E1.SD <= T.WD)
end
however T-Sql does not seem to like my Case statement mixed into my From/join clauses.
Thanks,
Mark E. Johnson
View 6 Replies
View Related
Dec 27, 2003
How do I return the updated value to client for this update?
UPDATE table SET x = x + 1 WHERE idvalue = y
View 1 Replies
View Related
Feb 5, 2004
Hi. This SHOULD be something simple, but I am apparently missing something. I have a Users table where a user's status is a varchar(100). I'm trying to implement a trigger so that when a user's status is changed to any string other than what it was before the update the trigger would change the LastUpdated field to current date/time.
Here's the trigger, I replaced the update of LastUpdated with a simple print statement. For some reason, it seems like the trigger is firing after the update statement has committed because the values of @m_status_new and @m_status_old are always the same so this trigger always prints 'status has not changed.' What am I doing wrong? Thank you greatly for any help provided.
USE myDB
IF EXISTS (SELECT name FROM sysobjects
WHERE name = 'tr_update_users' AND type = 'TR')
DROP TRIGGER tr_update_users
GO
CREATE TRIGGER tr_update_users
on dbo.Users
FOR UPDATE
AS
DECLARE @m_status_new varchar(100),
@m_status_old varchar(100),
@m_UserID int
SELECT @m_status_new = UserStatus,
@m_UserID = UserID
FROMinserted
SELECT @m_status_old = UserStatus
FROMUsers
WHEREUserID = @m_UserID
IF @m_status_new != @m_status_old
BEGIN
print 'status has changed'
END
ELSE
BEGIN
print 'status has not changed'
END
GO
View 6 Replies
View Related
Sep 10, 2007
Hi,
I am sending variables from package to package by configuration parent packages in each package...
I usually set logging to text files in a certain path that should be received from the parent variable... the strange thing is that if i let the variable in the child package with an incorrect path, my package just through an error even if i am passing the variable from the parent with a correct value...
So... my question is... does my package starts execution without any synch over the parent packages? When are they set? How can i be sure to start my logging with the right parent variable settings?
You can try for example to create a package... add a new variable like "A" and "B" set its value to a default string like "I DONT WANT THIS", add an Execute SQL Task that will record the values of "A" variable to a temporary table...
Then use dtexecui.exe to execute the package and set variable "A" to "THIS IS WHAT I NEED" you will see that in the table will appear one record with the "I DONT WANT THIS" value...
I can't understand this...
Also... if i have 100 variables configured to get values from the parent... is the execution synch or asynch?
Best Regards,
View 5 Replies
View Related
Nov 7, 2007
This is an error that popped up with after setting option strict to on
option strict disallows late binding
The error is on the field in red
If customer_data_reader("CustID") = (customer_bindingsource.Current("CustID") Then
i was looking at this but i cannot find what type this is exactly
If CStr(customer_data_reader("CustID")) = Ctype(customer_bindingsource.Current("CustID"), ????????) Then
It is a field, but how would i set the type for this?
Or do i need to do something different?
Thanks
Jeff
View 2 Replies
View Related
Oct 26, 2006
I'm trying to generate the data for a 2-column table, where both columns are defined as NOT NULL and the second column is a uniqueidentifier.
In SQL Server Management Studio, this works fine:insert into table_3(column_a, column_b)
select table_1.column_a, (case when table_2.column_b is NULL then newid() else table_2.column_b end) as column_b
from table_1 left outer join table_2 on table_1.column_c = table_2.column_c
That is, column_b of the SELECT result has no NULL values, and all 35,986 rows are successfully inserted into a previously empty table_3. (If I comment out the INSERT INTO clause and project table_2.column_b instead of "(case ... end) as column_b", the SELECT result includes 380 rows with a NULL in column_b, so I know the case expression plus the outer join are working as expected.)
But when I use the SELECT query as the SQL command in an OLE DB Source component that is connected directly to the OLE DB Destination for the result table, I get this error:There was an error with input column "column_b" (445) on input "OLE DB Destination Input" (420
The column status returned was: "The value violated the integrity constraints for the column.".
And sure enough, when I modify the result table to allow NULL in column_b, truncate it, and re-run the data flow, it inserts the exact same 380 rows with a NULL in column_b among the 35,986 rows.
So what is SSIS doing to screw up the results of the SELECT command???
View 6 Replies
View Related
Sep 10, 2005
Hi,Sorry for the obscure title but I'm afraid I can't think of a betterway to describe what happened to one of my clerks last night. The guy wasworking late, made a series of changes (accross a number of tables with adependant relationship structure - i.e. a customer linked to an order linkedto an invoice linked to a payments etc.) Now when he came back this morningnone of the work he did last night was still there. I'm by no means asql-pro - but I've managed to make do so far. Here's what I know:1) All of our records in all of our tables have date/time stamped. Once whenthey go in and once when they're changed. So with a little work I can buildup a good picture of what usage our database gets at what times. I've pulledup a query and there is a big fat hole between 8pm-10pm - stuff thathappened before that is still there, stuff that happened after that is stillthere - but all the changes that were put in between then just aren't thereany more. So it's not just insertions but updates as well.2) There is no perceivable break in our identity columns. So despite thefact that I know he entered 7 new customers, I can go back through thecustomers table and look at where those customers should sit visa vie entrytimes - and it's just as though the customers he entered never existed -sql server just keeps incrementing sequentially and there's no break - sothe last customer entered at about 6:50 pm was something like number 11912and the customers entered this morning have numbers that carry on from11913.3) I'm running in a shared environment - the server is hosted by awebhosting company (who shall remain nameless unless I can prove it's theirfault!) based in the US - the server has 100's of other Users databasesrunning on it.I just don't know where to begin diagnosing this sort of problem. But it hasme really running scared. It's not the first time something like this hashappened to me (i've noticed it once before when I had to get a connectionkilled by the people who manage our server because of a long-running querythat seemed to have just got bunged up and was locking a key table) - butthat was just a few records changed by the user who's connection got killed.Nothing like this... but it's pretty scary - I've got no way of knowing thatI'm losing changes like this on a continuous basis. It's my worstnightmare - like a pipe leaking underneath a floor board - and you only findout when the water starts running down the stairs!Has anyone got any ideas? Any starting places? Anyone else had anything likethis happen to them before?ThanksNick
View 5 Replies
View Related
Aug 12, 2012
An error is entered into the table, across two tables - tblErrors_ER and tblPolicyNumbers_ER - each error generates a PK (ErrorID) and can have any number of policy numbers which will be referenced by its own PK but linked to each error by its FK (ErrorID).I want to display each error in a Gridview in ASP.Net - columns included will be ErrorID, ErrorType, DateLogged from tblErrors_ER and PolicyNumber from tblPolicyNumbers_ER.If an Error has more than one policy number I only want to show the error once in the GridView with the word MULTIPLE under policy number.
tblErrors_ER
---------------
CREATE TABLE tblErrors_ER
{
ErrorID int,
ErrorType varchar(255),
DateLogged datetime,
[code]...
I have changed the Count(*) to Count(tblPolicyNumbers_ER.POlicyNUmber) which gives me the same undesired result as above. I have also left it as Count(*) and the entire CASE expression within the GROUP BY statement as suggest above which generated an error saying I can not use an expression in a group by clause.
If I leave Count(*) = 1 where it is in the original SELECT statement but swap the = for > then something happens, close to what I require but not as intended. It returns:
ErrorID ErrorType DateLogged PolicyNumber
---------------------------------------------------------------
1 Test 08/08/2012 Multiple
2 Test 08/08/2012 Multiple
this would suggest the original syntax is close to being accurate but I can not get it to work.
View 2 Replies
View Related
Jul 20, 2015
I have data that I want at multiple granularities, 5,15,30 and 60 minutes. To reduce repetition, I have put them all in the same table, so that there is a column for 5,15,30 and 60 minutes, with a filtered index on each of the columns that removes the nulls. This means that each day will have 288 slots, but only 24 of the slots are filled in for 60 min data, and all of them are filled for 5 minute data.
I have another column that specifies the interval granularity, and my first thought was to access my data through a join, where I can use a CASE statement, and depending on the data granularity necessary, it will look at a different column:
INNER JOIN Data d ON
AND d.settlement_key =
CASE st.interval_granularity
WHEN 5 THEN [5_min_settlement_key]
WHEN 15 THEN [15_min_settlement_key]
WHEN 60 THEN [60_min_settlement_key]
ELSE NULL END
Despite the presence of the indexes on the columns, then the process seems to be quite slow, I think probably due to the fact that any query plan isn't going to know beforehand which of the columns it is going to use for any given dataset, until it actually starts to run, so it may not be optimised.
How I could optimise this based on the given structure? Maybe there are hints to be added to the join, or maybe I can clear the query plan each time the SQL is run? My other option for dealing with the data of different granularity was to use one column and repeat the data multiple times, each at the different granularity, but this makes my data, row and table sizes much higher, as we are adding just a column for each additional granularity. Would this work any better in future versions of SQL server, maybe with column store indexes?
View 5 Replies
View Related
Nov 11, 2015
Any sql script or powershell script which outputs late running jobs? Currently I am using the below script to find out currently running jobs along with duration. But my requirement is to add few more columns to the query which indicates whether jobs is running fine or running behind expected time.
-currently using query to pull running jobs
SELECT
ja.job_id,
j.name AS job_name,
ja.start_execution_date,
ISNULL(last_executed_step_id,0)+1 AS currently_executing_step_id,
[code]...
View 4 Replies
View Related
Apr 30, 2008
Hello
Can any one tell me the difference between Cross Join, inner join and outer join in laymans language
by just taking examples of two tables such as Customers and Customer Addresses
Thank You
View 1 Replies
View Related
Aug 31, 2015
How can I change my T-SQL text editor from text sensitive to text insensitive?
View 2 Replies
View Related
Jan 6, 2005
Hello:
I have created an SQL server table in the past on a server that was all case sensative. Over time I found out that switching to a server that is not case sensative still caused my data to become case sensative. I read an article that said you should rebuild your master database then re-create your tables. So after rebuilding the master database, a basic restore would not be sufficient? I would have to go and manually re-create every single table again?
Any suggestions?
View 4 Replies
View Related
May 4, 2007
Can someone point me to a tutorial on how to search against a SQL Server 2000 using a case insensitive search when SQL Server 2000 is a case sensitive installation?
thanks in advance.
View 3 Replies
View Related
Aug 17, 2005
We need to install CI database on CS server, and there are some issueswith stored procedures.Database works and have CI collation (Polish_CI_AS). Server hascoresponding CS collation (Polish_CS_AS). Most queries and proceduresworks but some does not :-(We have table Customer which contains field CustomerID.Query "SELECT CUSTOMERID FROM CUSTOMER" works OK regardless ofcharacter case (we have table Customer not CUSTOMER)Following TSQL generate error message that must declare variable @id(in lowercase)DECLARE @ID INT (here @ID in uppercase)SELECT @id=CustomerID FROM Customer WHERE .... (here @id in lowercase)I know @ID is not equal to @id in CS, but database is CI and tablenames Customer and CUSTOMER both works. This does not work forvariables.I suppose it is tempdb collation problem (CS like a server collationis). I tried a property "Identifier Case Sensitivity" for myconnection, but it is read only and have value 8 (Mixed) by default -this is OK I think.DO I MISS SOMETHING ????
View 4 Replies
View Related
May 29, 2008
I am working in a SQL server database that is configured to be case-insensetive but I would like to override that for a specific query. How can I make my query case-sensitive with respect to comparison operations?
Jacob
View 5 Replies
View Related
May 4, 2015
I have column with value of all upper case, for example, FIELD SERVICE, is there anyway, I can convert into Field Service?
View 7 Replies
View Related
Aug 19, 2007
I am curious with using replication in sql server 2005 one way from db A (source) replicating to db B(destination) in which db A has a collation of CS and db B has a collation of CI. Will there be any problems with this scenario? Thanks in advance!
View 2 Replies
View Related
Nov 5, 2007
I have a view where I'm using a series of conditions within a CASE statement to determine a numeric shipment status for a given row. In addition, I need to bring back the corresponding status text for that shipment status code.
Previously, I had been duplicating the CASE logic for both columns, like so:
Code Block...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,
shipment_status_text =
CASE
[logic for condition 1]
THEN 'Condition 1 text'
WHEN [logic for condition 2]
THEN 'Condition 2 text'
WHEN [logic for condition 3]
THEN 'Condition 3 text'
WHEN [logic for condition 4]
THEN 'Condition 4 text'
ELSE 'Error'
END,
...remainder of SQL view...
This works, but the logic for each of the case conditions is rather long. I'd like to move away from this for easier code management, plus I imagine that this isn't the best performance-wise.
This is what I'd like to do:
Code Block
...beginning of SQL view...
shipment_status =
CASE
[logic for condition 1]
THEN 1
WHEN [logic for condition 2]
THEN 2
WHEN [logic for condition 3]
THEN 3
WHEN [logic for condition 4]
THEN 4
ELSE 0
END,
shipment_status_text =
CASE shipment_status
WHEN 1 THEN 'Condition 1 text'
WHEN 2 THEN 'Condition 2 text'
WHEN 3 THEN 'Condition 3 text'
WHEN 4 THEN 'Condition 4 text'
ELSE 'Error'
END,
...remainder of SQL view...
This runs as a query, however all of the rows now should "Error" as the value for shipment_status_text.
Is what I'm trying to do even currently possible in T-SQL? If not, do you have any other suggestions for how I can accomplish the same result?
Thanks,
Jason
View 1 Replies
View Related
Sep 6, 2007
I am working on a C#/asp.net web application. The application has a text box that allows a user to enter a name. The name is then saved to the database.
Before the name is saved to the database, I need to be able to check if the name already exists in the database. The problem here is that what if the name is in the database as "JoE ScMedLap" and somoene enters the name as "Joe Schmedlap" which already exists in the database,but just differs in case.
In other words how do deal with case sensitiviy issues.
View 2 Replies
View Related
Jul 20, 2005
Yesterday I received a response to my CI/CS Collation problem and therecommendation was to try and restore a CI Collation database to a CSCollation database. After creating a blank CS database a full restore(Force restore over existing database) does change the Collation toCI. I'm unsure as to how I can restore without changing theCollation. Any suggestions?
View 2 Replies
View Related
May 22, 2015
I have two xml source and i need only left restricted data.
how can i perform left restricted join?
View 2 Replies
View Related
Oct 8, 2015
I was writing a query using both left outer join and inner join. And the query was ....
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT
S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
View 5 Replies
View Related
Dec 23, 2014
I have two select statements, in between select statement taking UNION ALL . I need to avoid the error
Warning: The join order has been enforced because a local join hint is used.
View 9 Replies
View Related
Aug 10, 2007
Scenario:
OLEDB source 1
SELECT ...
,[MANUAL DCD ID] <-- this column set to sort order = 1
...
FROM [dbo].[XLSDCI] ORDER BY [MANUAL DCD ID] ASC
OLEDB source 2
SELECT ...
,[Bo Tkt Num] <-- this column set to sort order = 1
...
FROM ....[dbo].[FFFenics] ORDER BY [Bo Tkt Num] ASC
These two tasks are followed immediately by a MERGE JOIN
All columns in source1 are ticked, all column in source2 are ticked, join key is shown above.
join type is left outer join (source 1 -> source 2)
result of source1 (..dcd column)
...
4-400-8000119
4-400-8000120
4-400-8000121
4-400-8000122 <--row not joining
4-400-8000123
4-400-8000124
...
result of source2 (..tkt num column)
...
4-400-1000118
4-400-1000119
4-400-1000120
4-400-1000121
4-400-1000122 <--row not joining
4-400-1000123
4-400-1000124
4-400-1000125
...
All other rows are joining as expected.
Why is it failing for this one row?
View 1 Replies
View Related