Using results of a SELECT to pull relevant values from another table - sql-server

I'm parsing a string from a table with the following query.
SELECT
CASE
WHEN jobdata LIKE '%DocFtpPassword%'
THEN SUBSTRING(jobdata,
CHARINDEX('DefColId=', jobdata) + 9,
CHARINDEX('|DocFtpPassword=', jobdata) - CHARINDEX('DefColId', jobdata) - 9)
ELSE 'No Import Library'
END AS 'Import_Library'
FROM
jobscompleted
What I want to do then is to take each row and pull another value via another table. I know I could just write out the same statement twice, as in,
SELECT
CASE
WHEN jc.jobdata LIKE '%DocFtpPassword%'
THEN SUBSTRING(jc.jobdata,
CHARINDEX('DefColId=', jc.jobdata) + 9,
CHARINDEX('|DocFtpPassword=', jc.jobdata) - CHARINDEX('DefColId', jc.jobdata) - 9)
ELSE NULL
END AS 'Import_Library',
c.collectionname
FROM
jobscompleted jc
JOIN
collection c ON CASE
WHEN jc.jobdata LIKE '%DocFtpPassword%'
THEN SUBSTRING(jc.jobdata,
CHARINDEX('DefColId=', jc.jobdata) + 9,
CHARINDEX('|DocFtpPassword=', jc.jobdata) - CHARINDEX('DefColId', jc.jobdata) - 9)
ELSE NULL
END = c.collectionid
but that obviously is super redundant. Is there a way to do this in a much more succinct and readable way, and bear in mind I don't really know anything about stored procedures or variables (although there's always a good time to learn).

Not sure if this is what you are asking for. If not, please provide more details to the question.
SELECT * FROM
(SELECT
CASE
WHEN jobdata LIKE '%DocFtpPassword%'
THEN SUBSTRING(jobdata,
CHARINDEX('DefColId=', jobdata) + 9,
CHARINDEX('|DocFtpPassword=', jobdata) - CHARINDEX('DefColId', jobdata) - 9)
ELSE 'No Import Library'
END AS 'Import_Library'
FROM
jobscompleted ) AS jc
INNER JOIN
collection c ON jc.Import_Library = c.collectionid

Related

How to modify multiple CASE statements

It's me again. I would just like to ask your opinion on how shall I modify my SELECT statament query. So basically I created a user defined field called "Force Schedule2", if this checkbox is tick (equals 1), then even if the item is on schedule 1, it will display on schedule 2. How shall I add it on my existing case statement?
my current SELECT statement is:
SELECT
CASE
WHEN
WorkOrder.DateCreated <
(
CASE
WHEN
(DATEPART(dw, dbo.ToBeScheduled_InProgress.Start) = 2)
THEN
(ToBeScheduled_InProgress.Start + 0.625) - 3
ELSE
(ToBeScheduled_InProgress.Start + 0.625) - 1
END
)
THEN
1
ELSE
2
END
AS ScheduleTime
and my user defined field for "Force Schedule2 is:
dbo.AdditionalInfo.UserDefined3 AS ForceSched
It's not obvious what you're trying to do here with your date operation. You could do something simple like this:
CASE
WHEN dbo.AdditionalInfo.UserDefined3 = 1
THEN 2
WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw, dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END)
THEN 1
ELSE 2
END AS ScheduleTime
Basically it hits the condition and exits the statement. If you flipped it so your date operation was first it would return 1, so you still need to think about the order you're entering things into case statement.

SQL how to check prefix in cell with two prefixes

I am learning SQL and I have a table where there are certain cells with two prefixes like this :
example1(cell) : R:8days; U:5$;
example2(cell) : R:8days;
example3(cell) : U:5$;
I want to check for that U:5$ after the first prefix, as I know how to check for prefix R:8days;. So I need to check for U:5$ and then make a new column in table.
My code looks like this:
;with cte as (
select
Employer, AmountPayd, AmountPayd as Payd
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%' **HERE I WANT TO CHECK FOR PREFIX NR2. 'U:5$' AND MAKE NEW COLUMN FOR WHICH EMPLOYER HAS U:5$ NOTE.**
)
select
Employer,
[4.00] = ISNULL([4.00],0)
,[5.00] = ISNULL([5.00],0)
,[9.00] = ISNULL([9.00],0)
,[10.00] = ISNULL([10.00],0)
,[15.00] = ISNULL([15.00],0)
,[Sum] =ISNULL([4.00],0) + ISNULL([5.00],0) + ISNULL([9.00],0) + ISNULL([10.00],0) + ISNULL([15.00],0)
from cte
pivot (
sum(AmountPayd) for Payd in ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00]))pvt;
This?
select
Employer, AmountPayd, AmountPayd as Payd,
CASE WHEN Note like '%R:8%;%U:5$%' THEN 'U:5' END U5Note
from data
where TipeOfTransaction like 'Offline Prepaid%' AND Note like '%R:8%'
(I've corrected some mistakes in column names and refactored the query.)
I believe, you are looking for something like this:
WITH CTE AS (
SELECT
Employer,
AmountPaid,
Paid
FROM Data
LEFT JOIN (VALUES (4, 5, 9, 10, 15, 20)) V(Paid)
ON Note LIKE '%U:' + CAST(Paid AS VARCHAR(10)) + '$;%'
WHERE TypeOfTransaction LIKE 'Offline Prepaid%'
AND Note LIKE '%R:8%'
)
SELECT
Employer,
ISNULL([4.00], 0) AS [4.00],
ISNULL([5.00], 0) AS [5.00],
ISNULL([9.00], 0) AS [9.00],
ISNULL([10.00], 0) AS [10.00],
ISNULL([15.00], 0) AS [15.00],
ISNULL([4.00] + [5.00] + [9.00] + [10.00] + [15.00], 0) AS Sum
FROM CTE
PIVOT( SUM(AmountPaid)
FOR Paid IN ([4.00],[5.00],[9.00], [10.00], [15.00], [20.00])) PVT;

SQL Invalid data is showing

t0212_1 t0212_2
884999999 GCP-9 Company A
8849999 GCP-7 Company B
#val = 884999999
Here's my query :
Select * Company
WHERE t0212_1= (LEFT(CONVERT(BIGINT,#val),convert(int,substring('GCP-9',5,2)))) OR
t0212_1= LEFT(CONVERT(BIGINT,#val),convert(int,substring('GCP-7',5,2)))
When I searched 8849999 , 8849999 shows(this is RIGHT).
When I searched 884999999 , 884999999 shows(this is RIGHT) and 8849999 shows(WRONG).
What to do, please help
Thanks,
If you dont understand my very short explanation you can verify it to me.
Your filteration is either 7 or 9 characters from the input (DECLARE #val INT = 884999999)
should match the column (t0212_1) value.
As per your filter, you would get two records since the two records matched on your filteration.
You can use this SQL
SELECT *
FROM #Company
WHERE t0212_1 = (LEFT(CONVERT(BIGINT, #val), convert(INT, substring(t0212_2, 5, 2))))

Getting invalid column name in SQL/Excel

I will preface this by saying I am nowhere near being an expert in SQL. Using Excel I am trying to use one specific cell as the input to query, but I run into a problem where a column I created isn't defined as a column. Please help.
SELECT
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END AS IPADDRESS,
ADMachine.ADMachineName, ADMachine.SerialNumber,
ADMachine.OperatingSystem, ADUsers.ADUser, ADUsers.ADDisplayName, employee_data.employee_first_name,
employee_data.employee_last_name, asset_center.LOCATION_SITENAME, asset_center.TCPIPHOSTNAME,
asset_center.MAC_ADDRESS, ADUsers.ADUserOU
FROM PC_GAP.dbo.ADMachine ADMachine, PC_GAP.dbo.ADUsers ADUsers, PC_GAP.dbo.asset_center asset_center, PC_GAP.dbo.employee_data employee_data
WHERE ADUsers.ADUser = employee_data.employee_user_name AND ADMachine.SerialNumber = asset_center.SERIALNO AND ADUsers.ADUser = asset_center.LAST_LOGGED_ON_USER
The IPAddress at the end is where the problem lies.
Edit 1: Added the additional information from the SQL statement to paint the whole picture (originally left out irrelevant data)
Alright so first off you need to stop using the old style joins for all of the reasons listed here.
You are also going to run into an issue that you aren't joining on anything other than one of your tables. I'm pretty sure this will not give you the results that you are looking for.
Then finally you need to think about the order of operations. Since the WHERE clause is evaluated before the the select you cannot refer to your alias in the where clause. You can only reference an alias with an ORDER BY or by using a subquery or a cte.
You can however use your case expression in your where clause. The example would be as follows.
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0
THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1)
ELSE TCPIPADDRESS
END = ?
As stated previously you could also turn this entire thing into a subquery. I would use your code as an example for that but I'm not entirely sure what exactly you're hoping to accomplish with your current set of joins so my example will be a bit generic.
select
GenericColumn
(select
blah as Pity,
GenericColumn
from dbo.TheFoo)
where Pity = SeachCondition
You can't use a column alias in the WHERE clause. You have to use the whole formula that you aliased.
WHERE ADMachine.SerialNumber = asset_center.SERIALNO AND ((CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END=?))
To illustrate Aaron's suggestion, it would look more like this:
WITH cte AS (
SELECT
CASE
WHEN CHARINDEX(',', TCPIPADDRESS) > 0 THEN LEFT(TCPIPADDRESS, CHARINDEX(',', TCPIPADDRESS) - 1) ELSE TCPIPADDRESS END AS IPADDRESS,
ADMachine.ADMachineName,
ADMachine.OperatingSystem,
asset_center.MAC_ADDRESS,
FROM PC_GAP.dbo.ADMachine ADMachine, PC_GAP.dbo.ADUsers ADUsers, PC_GAP.dbo.asset_center asset_center, PC_GAP.dbo.employee_data employee_data
)
SELECT * FROM cte
WHERE ADMachine.SerialNumber = asset_center.SERIALNO AND ((IPAddress=?))

Missing data row in NOT IN clause

I just realised that my Auto-Price Calculation doesn't fill the Prices for ListID 4.
I inserted the Prices from the SELECT shown below.
For bugg research I executed the SELECT without the WHERE part and it shows me the example data row.
I can't find the error though, why it is not shown in the complete select (it has no entry with ListID = 4).
Someone can see my mistake?
Edit: Just tried the subselect alone, it shows no rows for the requested article. Why is the NOT IN clause unaffected by this fact?
Most likely, it's because of how you are combining the artikelnummer and the auspraegungID.
I do not think you have accounted for that fact that '100' + '0' is idential to '10' + '00'.
Instead of trying to merge two fields into one, perhaps try the following?
SELECT
*
FROM
#allArticles AS allArticles
WHERE
Artikelnummer = 'IT-810260'
AND NOT EXISTS (SELECT *
FROM KHKPreisListenArtikel
WHERE ListeID = 4
AND Artikelnummer = allArticles.Artikelnummer
AND Auspraegung = allArticles.Auspraegung
)
If that still doesn't work, then you must have corresponding records in that other table, find them like this...
SELECT
*
FROM
#allArticles AS allArticles
INNER JOIN
KHKPreisListenArtikel AS Preis
ON Preis.ListeID = 4
AND Preis.Artikelnummer = allArticles.Artikelnummer
AND Preis.Auspraegung = allArticles.Auspraegung
WHERe
allArticles.Artikelnummer = 'IT-810260'
PLEASE ALSO NOTE
Please don't include images of code, please copy the code, so that we can copy it too.
Especially when the tables/fields are in another language...
EDIT
Here is a query that will show the cause of your original query to fail.
SELECT
*
FROM
#allArticles AS allArticles
INNER JOIN
KHKPreisListenArtikel AS Preis
ON Preis.ListeID = 4
AND Preis.Artikelnummer + CONVERT(VARCHAR(50), Preis.Auspraegung)
=
allArticles.Artikelnummer + CONVERT(VARCHAR(50), allArticles.Auspraegung)
WHERE
allArticles.Artikelnummer = 'IT-810260'

Resources