Add Increment to create a path on SQL to be used for a CrystalReport - sql

I am trying to come up with a the correct path for my Crystal report to pick the correct .pdf files. Here is what I have on SQL:
CASE
WHEN pd.pdCode like 'CUST%'
THEN 'Y:\300 ORDER PROCESSING\Majid Ahmadi\' + CAST(ord.ordPONumber as nvarchar(25)) + '_Custom' + '.pdf' --Added 2018-05-23 by MA
ELSE Null
END AS imageFilePath
And results:
Y:\300 ORDER PROCESSING\Majid Ahmadi\53244_Custom.pdf
Problem is I have multiple files that I want to pick. Like:
enter image description here
(picture in the link)
Any suggestion to modify my path?

Could use change the THEN to
THEN 'Y:\300 ORDER PROCESSING\Majid Ahmadi\' + CAST(ord.ordPONumber as nvarchar(25)) + '_' + pd.pdCode + '.pdf'

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-

Dynamic XML node name in SQL XML

I am updating an XML column with values from columns in a temp table. I can update the table as below.
UPDATE tbWorkflow
SET xmlData.modify('insert
(<FromQueueName>
<CustomerID>{ sql:column("T.iVTollCustID") }</CustomerID>
<Date>{ sql:variable("#CurrDateTime") }</Date>
</FromQueueName>)
as first into (/configuration)[1]'),
vcQueue = 'qVtoll',
dtUpdTime = GETDATE()
FROM #Trxns T
WHERE T.biWorkflowID = tbWorkflow.biWorkflowID
However, I want the node name to be dynamic (from the temp table) like below. But it does not work.
UPDATE tbWorkflow
SET xmlData.modify('insert
(<**{ sql:column("T.vcQueue") }**>
<CustomerID>{ sql:column("T.iVTollCustID") }</CustomerID>
<Date>{ sql:variable("#CurrDateTime") }</Date>
</**{ sql:column("T.vcQueue") }**>)
as first into (/configuration)[1]'),
vcQueue = 'qVtoll',
dtUpdTime = GETDATE()
FROM #Trxns T
WHERE T.biWorkflowID = tbWorkflow.biWorkflowID
Any help is appreciated.
I think, you should use a subquery to select a string you need and then insert it into XML.
For example, in subquery get a <YourTag><CustomerID>123</CustomerID><Date>15.10.2012</Date></YourTag> and then you can simply insert it in XML
I found a workaround to do this.
I added another VARCHAR column to my temp table, created the xml node as a varchar and later modified my actual xml column using this varchar column.
UPDATE #Trxns
SET xmlVarchar = '<' + vcQueue + '>
<CustomerID>' + CONVERT(VARCHAR(10),iVTollCustID) + '</CustomerID>
<Date>' + CONVERT(VARCHAR(25), GETDATE(),22) + '</Date>' +
'</' + vcQueue + '>'
UPDATE tbWorkflow
SET xmlData.modify('insert
sql:column("xmlVarchar")
as first into (/configuration)[1]'),
vcQueue = 'qVtoll',
dtUpdTime = GETDATE()
FROM #Trxns T
WHERE T.biWorkflowID = tbWorkflow.biWorkflowID

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;

Using carriage return or line feed to build message body with tsql

I have the following tsql that sends db mail. This works with one formatting exception. The last two lines generated do not have a line feed or carriage return in the email body. The data types are varchar(255) and varchar(300) respectively.
I have tried with and with out cast and I have tried CHAR(10), CHAR(13) separately and together.
Why does these last two NOT split into separate lines?
DECLARE #errMsg VARCHAR(max)
-- review edit fact UMDNSID values and catch orphans with out parents in CategoryList
select #errMsg =
'====================================================================' + char(10) +
'Orphan UMDNSID: ' + cast(ef.umdnsid as varchar(50)) + char(10) +
'Edit Fact VendorItemID: ' + cast(ef.vendoritemid as varchar(50)) + char(10) +
'Current VendorItem UMDNSID: ' + cast(ip.umdnsid as varchar(50)) + char(10) +
'Current VendorItem Category: ' + ipcl.categoryname + char(10) +
'Item Description: ' + ef.LongDescription + char(10) + char(13)
from EditFact ef
join itemprovider ip
on ef.vendoritemid = ip.itemprovider_pk
join categorylist ipcl
on ipcl.umdnsid = ip.umdnsid
where 1=1
AND editstatusid = 0
AND settled is null
AND ef.UMDNSID not in (
select umdnsid from categorylist)
EXEC dbo.ProcessFile_SendMail #ProcessFile_id=0, #Subject='Orphan UMDNSID', #Message=#errMsg, #To='someone#email.com';
The email body ends up looking like the following and I expect a new line where you see **.
Orphan UMDNSID: 27854
Edit Fact VendorItemID: 4654178
Current VendorItem UMDNSID: 99936
Current VendorItem Category: Custom Packs **Item Description: TRAY CARDIAC CATH CUSTOM
In case that was the final answer
Test a print(#errMsg).
The problem may be in ProcessFile_SendMail.