Varchar and Body help on DB2 - sql

I have a query that I made that pulls data from a form that is being submitted by my drivers
SELECT DRIVER, POWER
,VARCHAR(SUBSTR(CAST(BODY AS VARCHAR(100)),LOCATE('FIELD:002',CAST(BODY AS VARCHAR(100))) + 9, (LOCATE('#FIELD:003',CAST(BODY AS VARCHAR(100))) - (LOCATE('FIELD:002',CAST(BODY AS VARCHAR(100))) + 11))),10) AS TRAILER
,VARCHAR(SUBSTR(CAST(BODY AS VARCHAR(100)),LOCATE('FIELD:003',CAST(BODY AS VARCHAR(100))) + 9, (LOCATE('#FIELD:004',CAST(BODY AS VARCHAR(100))) - (LOCATE('FIELD:003',CAST(BODY AS VARCHAR(100))) + 11))),10) AS REASON
,VARCHAR(SUBSTR(CAST(BODY AS VARCHAR(100)),LOCATE('FIELD:004',CAST(BODY AS VARCHAR(100))) + 9, (LENGTH(CAST(BODY AS VARCHAR(100))) - (LOCATE('FIELD:004',CAST(BODY AS VARCHAR(100))) + 10))),50) AS DESCRIPTION
FROM VMC_RETNO2 WHERE MESSAGE_ID = '21021590' WITH UR
and this is how it looks in my data base!
#FIELD:001
#FIELD:002
#FIELD:003 5-Other
#FIELD:004
This query works great however when I try to manipulate the query so it pulls data for another form nothing returns, can you guys help me out? Thanks in advance
This is how the data looks that I need
Freight Bill:99095648
Master BOL#1:1111111111
Master BOL#2:2222222222
Master BOL#3:3333333333
Weight:10464
MSF:736.234

Related

How can I check the maximum value from a set of tables in SQL Server (if possible)?

We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:
EDIT: all the databases are on the same server.
The DB1.dbo.tblProfessions is like:
intProfessionCode
strProfessionDescription
1
lawyer
2
dentist
...
...
30
doctor
And the DB72.dbo.tblProfessions is as follows:
intProfessionCode
strProfessionDescription
1
designer
2
butcher
...
...
80
chef
Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).
By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:
SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;
Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.
Thanks in advance.
You should be able to do something like this:
WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall
For situations like this, I usually query the catalog to write the above script rather than typing it out:
WITH
dat AS
(
SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
MAX(intProfessionCode) AS max_intProfessionCode
FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
UNION ALL',' ') AS s
FROM sys.databases s
WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
)
SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
FROM dat;
Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.

How to select into table as string builder instead of using cursor in SQL

I am wondering if there is a faster way to handle the following code in SQL. Currently I am using SQL cursor to do a select and build a string of delimiter values, as a dynamic value of suggestion items?
Here is the snippet of SQL:
begin
set #cursor = cursor for
select top 5 Manufacturer,ManufacturerPartNumber,Description as ManufacturerDescription, CONVERT(money,Price) as Price,fms.Score
from Products_OurProducts_Products_View
open #cursor
fetch next from #cursor
into #CURSOR_Mfr,#CURSOR_Model,#CURSOR_Desc,#CURSOR_Price,#CURSOR_Score
while ##FETCH_STATUS = 0
begin
set #suggestionsStringBuilder += #CURSOR_Mfr + ',' + #CURSOR_Model + ',' + #CURSOR_Desc + ',' + convert(varchar(20),#CURSOR_Price) + ',' + convert(varchar(4),#CURSOR_Score) + '^'
fetch next from #SuggestionsListCursor
into #CURSOR_Mfr,#CURSOR_Model,#CURSOR_Desc,#CURSOR_Price,#CURSOR_Score
end
insert into BASE (Manufacturer, ManufacturerOrig, ManufacturerPartNumber,ManufacturerPArtNumberOrig,ManufacturerDescription, QWDescription, Serial,AssetID,Price,Score,ItemType,MfrFound,ModelFound,trained, SuggestionList,LineNumberIn)
values(#objectORIGMfr,#objectORIGMfr, #objectORIGModel, #objectORIGModel, #objectDescription, #objectDescription, '',#objectAssetID,'0.00',#topMaxScore,'NA','1','0',#trained,#suggestionsStringBuilder,#objectLineNumber)
close #cursor
deallocate #cursor
end
The code above is trying to build a dynamic column of delimiter values such as shown below:
Object Example:
Mfr,
Model,
Price,
Score,
Description,
Suggestions = 'Mfr,Model,Desc,Price^Mfr,Model,Description,Price^
A return model would truly be as follows:
BaseMfr:Fluke,
BaseModel:Tb1,
BaseDescription:'Multi meter item',
BasePrice:120.00,
Suggestions: "Fluke, Tc1, 'Desc', '120.00' ^ 'Fluke', 'T11', 'Desc', 220.00"
Can I do the string builder / cursor section without having to use a looping cursor? The idea behind this is we send in items to be priced. If the item is not found, we then build a list of suggestions to bring back to the user of what they may use in the system or so they can see if there is a typo in the data.
The suggestion list is just the rows found, separating the columns by a "," and separating entities by a "^".
Thanks very much in advance!
Thanks you all for the feedback and I appreciate the help even though I know I had a rough time explaining the question correctly. Thanks to the suggestion from Sean Lange, I was able to be directed in the correct direction and came up with this. Now I will test the performance of it to see if it is better or not. Here is the code:
select
SUBSTRING(
(select top 5
Manufacturer + ',' + ManufacturerPartNumber + ',' + Description +',' + CONVERT(VARCHAR,Price) +',' + CONVERT(varchar,fms.Score) +'^' as [text()]
from Products_OurProducts_Products_View
CROSS APPLY (
select
dbo.FuzzyControlMatch('Flooke', Manufacturer) AS score
) AS fms
order by fms.score desc
FOR XML PATH ('')
), 2, 1000) [Suggestions]
The above code produces the following string:
ARD BROOKE,WB808 10UNF,TORQUE SCREWDRIVER,70.00,50^WARD BROOKE,WB808 1146,TORQUE SCREWDRIVER,70.00,50^WARD BROOKE,WB808 1246,TORQUE SCREWDRIVER,70.00,50^WARD BROOKE,WB808 6UNC,TORQUE SCREWDRIVER,70.00,50^ROKEM TECHNOLOGIES,FIRESET,RC STANDARD,105.00,50^
Now I am not sure if I am handling this the best way, but this is what I was searching for. I will post a comment update to let the feed know if the performance is better or worse.
-Thanks-

Convert date from AS/400 database file

I'm using MS SQL Server and am Trying to convert the date and time data into something useful for PowerBi and
can't get the time to work, Date is fine:
USE [CDCP_AEP]
GO
select *
from
(SELECT [H1PROD]
,convert(DATE,right('0'+str([H1DTTR],len([H1DTTR])),6),102) as 'AssyDate'
,[H1TMTR]
,right('000000'+str([H1TMTR],len([H1TMTR])),6) 'TempTime'
,[H1TYPE]
,[H1LOT]
,[H1SORD]
from [AEBPCSUSRF].[JHP1]
where [H1TYPE] = 'AF' and [H1LOT] <> '')a
left join
(select [P1PROD]
,[P1LOT]
from [AEBPCSUSRF].[PLA1])b
on a.[H1LOT] = b.[P1LOT]
GO
This is the result I get with the above code:
If I change the date (H1TMTR) line to
,convert(TIME,right('000000'+str([H1TMTR],len([H1TMTR])),6)) as 'AssyTime'
I get the following error:
"Msg 241, Level 16, State 1, Line 4
Conversion failed when converting date and/or time from character string."
Any tips? Thanks in advance!
You can convert by padding, substring'ing, and putting colons in between the parts like so:
DECLARE #H1TMTR VARCHAR(6)='155509'
SELECT CONVERT(TIME,
SUBSTRING(RIGHT('000000' + #H1TMTR,6),1,2) + ':'
+ SUBSTRING(RIGHT('000000' + #H1TMTR,6),3,2) + ':'
+ SUBSTRING(RIGHT('000000' + #H1TMTR,6),5,2)
) AS [Time]
Since you are doing this for PowerBI, I presume you will be doing this quite a bit. You should make a scalar function that performs this task on a column so it only needs written once.

Why doesn't this GROUP BY query work?

I'm querying my Access table with this query:
SELECT (VIN&' '&Make&' '&Model&' '&CarYear&' '&ExColor&' '&InColor&' ')as CarDescript
FROM TestTable
WHERE (WorkOrderNumber='$workorder')
GROUP BY AssignedEmp;
But a similar type of query works just fine in this SQL Fiddle
Even if I replace the long (VIN&' '&....) with VIN it still doesn't work.
EDIT: Schema of the table is
WorkOrderNumber - Priority - JobStage - WorkItem - AssignedEmp - DueDate - VIN - Make - ... - InColor
In general use + instead of & for SQL. (Access will allow this however).
In a group by you need to pick which one in the group to use (if you are using mysql like your example it just picks a random one, see this fiddle) so to fix this in the general case for your example:
SELECT (max(VIN) + ' ' + max(Make) + ' ' + max(Model) + ' ' + max(CarYear) + ' ' + max(ExColor) + ' ' + max(InColor) + ' ')
as CarDescript
FROM TestTable
WHERE WorkOrderNumber='$workorder'
GROUP BY AssignedEmp;

Natural sort with SQL Server

I want to convert the order of the values with column name PTNT_VST_CSNO from the following :
VMIP1
VMIP10
VMIP11
VMIP2
VMIP20
VMIP21
VMIP3
VMIP31
VMIP32
VMIP5
VMIP6
VMIP7
VMIP8
VMIP9
VMOP10
VMOP11
VMOP12
VMOP3
VMOP30
VMOP31
VMOP32
VMOP4
VMOP40
VMOP41
VMOP42
VMOP43
VMOP7
VMOP70
VMOP71
VMOP8
VMOP9
to:
VMIP1
VMIP2
VMIP3
VMIP5
VMIP6
VMIP7
VMIP8
VMIP9
VMIP10
VMIP11
VMIP20
VMIP21
VMIP31
VMIP32
VMOP3
VMOP4
VMOP7
VMOP8
VMOP9
VMOP10
VMOP11
VMOP12
VMOP30
VMOP31
VMOP32
VMOP40
VMOP41
VMOP42
VMOP43
VMOP70
VMOP71
I want to sort the numeric part of 'vmip' first then that of 'vmop'.. I tried a lot but failed every time. kindly help me guys to sort out the sorting problem... thank you in advance
Not the fastest thing in the world, but it should get the job done:
ORDER BY CASE WHEN PTNT_VST_CSNO LIKE 'vmi%' THEN 0 ELSE 1 END
,CAST(replace(replace(PTNT_VST_CSNO, 'vmip', ''), 'vmop', '') as int)
After great trial, I succeeded to solve it with the following way..
SELECT ptnt_vst_csno
FROM table_name
ORDER BY Substring(ptnt_vst_csno, 1, Charindex('P', ptnt_vst_csno)),
CONVERT(INT, Substring(Substring(ptnt_vst_csno,
Charindex('P', ptnt_vst_csno),
Len(
ptnt_vst_csno)), 2, Len(
ptnt_vst_csno)))
the easiest way to accomplish this would be to change your numering to 3 digits.
i.e. 1 would become 001, 2 would become 002, 10 would become 010, and so on...
this would then allow you to order the data correctly.
you might want to do something like this:
SELECT
PTNT_VST_CSNO,
'VMIP' + CASE LEN(REPLACE(PTNT_VST_CSNO, 'VMIP', ''))
WHEN 1 THEN '00' + REPLACE(PTNT_VST_CSNO, 'VMIP', '')
WHEN 2 THEN '0' + REPLACE(PTNT_VST_CSNO, 'VMIP', '')
ELSE REPLACE(PTNT_VST_CSNO, 'VMIP', '')
END
FROM
TableName
WHERE
LEFT(PTNT_VST_CSNO, 4) = 'VMIP'
ORDER BY
2