Display file path of documents in Crystal Report - sql-server

I have a crystal report that lists invoices and I would like to be able to show the file path of the invoices in another column of the report. The following query allows me to search for the documents based on their unique ID number. It then displays the file location of the one document I search for, however I would like to have this apply to all of the documents listed in the report. Can someone please help me out with this?
`DECLARE #entryID INT = 35793
SELECT dbo.toc.name AS DocumentName, dbo.doc.pagenum + 1 AS PageNum, dbo.vol.fixpath + '\' +
SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),1,2) + '\' +
SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),3,2) + '\' +
SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),5,2) + '\' +
CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2) + '.TIF' AS FullPathAndFilename
FROM dbo.doc
LEFT JOIN dbo.toc ON dbo.doc.tocid = dbo.toc.tocid
LEFT JOIN dbo.vol ON dbo.toc.vol_id = dbo.vol.vol_id
WHERE dbo.doc.tocid = #entryID
ORDER BY dbo.doc.pagenum`

The answer depends on how you currently retrieve data in the existing Crystal Report.
Option A: If your report data source is a "Command" (in other words you have written a SQL statement in the crystal report that retrieves the data you need), then you will want to modify that command to pull in this new information via a subquery. So for example if your current report SQL is something like "select x.* from foo as x", you would want it to be something like:
select x.*,
(SELECT dbo.vol.fixpath + '\'
+ SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),1,2) + '\'
+ SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),3,2) + '\'
+ SUBSTRING(CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2),5,2) + '\'
+ CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), dbo.doc.storeid),2)
+ '.TIF' AS FullPathAndFilename
FROM dbo.doc
LEFT JOIN dbo.toc ON dbo.doc.tocid = dbo.toc.tocid
LEFT JOIN dbo.vol ON dbo.toc.vol_id = dbo.vol.vol_id
WHERE dbo.doc.tocid = x.tocid //this line joining the new SQL to all report rows
)
from foo as x;
Option B: If instead you pull your data from Crystal using the join wizard, then it would probably be best to create a new view in your database that matches the SQL you provided (minus the last 2 lines), and then join your existing main report tables to this view in the Crystal join wizard.

Related

SQL Server trigger reports 'inserted' table is missing

I am running a script against a SQL Server 2016 database that creates various tables, views and triggers. This same script has been working against dozens of other servers but it is getting an error against this one particular server.
All of the triggers seem to be created but when I check for invalid objects it reports all of them as invalid. The really strange part is, it says the problem is the "inserted" table (or "deleted" table, depending on the trigger) is missing.
I am checking for invalid objects using this query:
SELECT
QuoteName(OBJECT_SCHEMA_NAME(referencing_id)) + '.'
+ QuoteName(OBJECT_NAME(referencing_id)) AS ProblemObject,
o.type_desc,
ISNULL(QuoteName(referenced_server_name) + '.', '')
+ ISNULL(QuoteName(referenced_database_name) + '.', '')
+ ISNULL(QuoteName(referenced_schema_name) + '.', '')
+ QuoteName(referenced_entity_name) AS MissingReferencedObject
FROM
sys.sql_expression_dependencies sed
LEFT JOIN
sys.objects o ON sed.referencing_id = o.object_id
WHERE
(is_ambiguous = 0)
AND (OBJECT_ID(ISNULL(QuoteName(referenced_server_name) + '.', '')
+ ISNULL(QuoteName(referenced_database_name) + '.', '')
+ ISNULL(QuoteName(referenced_schema_name) + '.', '')
+ QuoteName(referenced_entity_name)) IS NULL)
ORDER BY
ProblemObject,
MissingReferencedObject
which I got from here
Find broken objects in SQL Server
The triggers are "instead of" triggers against the views that then modify the underlying tables. There is really nothing special about any of them.
Is there something wrong with my query and the objects aren't really invalid or is there something with the database? I am running the script as the database owner so I don't think it is a permissions issue.
Thanks
Run this query against the problem SQL Server, and against one where no problems are shown:
SELECT *
FROM
sys.sql_expression_dependencies sed
LEFT JOIN
sys.objects o ON sed.referencing_id = o.object_id
WHERE type = 'TR'
ORDER BY
type_desc,
referenced_entity_name
If the inserted / deleted tables show up in one list but not the other, then there is some difference causing this. I'd check identifier quoting rules to start.

SQL - WHERE statement with text added to value from table

I need to copy data from an old database to a newer one.
Both of these databases have a user setup table with the primary key of "USER ID".
The problem is, in the old database the users didn't have the domain in the name, but in the new one they have.
Example:
Primary Key old DB: USER1
Primary Key new DB: DOMAIN\USER1
This prevents a standard WHERE clause to update the correct user because it can't find it due to the domain being added.
My code:
'FROM [' + #src_DB + '].dbo.[' + #src_table + '] as src '
'WHERE [' + #dest_DB + '].dbo.[' + #dest_table + '].[User ID] = ' + #domain_name + 'src.[User ID]'
printing the result:
WHERE [Destination_DB].dbo.[Destination_Table].[User ID] = DOMAIN\src.[User ID]
The problem is it doesn't add the DOMAIN to the value but rather to the statement...
How can I add the Domain to the actual value of src.[User ID]?
I think there's a dot missing, and you should use QUOTENAME
'WHERE ' + QUOTENAME(destination_table) + '.[User ID] = ' + QUOTENAME(#domain) + '.' + QUOTENAME(source_table) + '.[User ID]'
Whenever you create a SQL statement dynamically it's a good idea to print it out, copy it into a new query window and check for syntax errors...
UPDATE You: Yes, both databases are in the same server
An object can be (fully) specified with
ServerName.DatabaseName.Schema.ObjectName
A table's column would add one more .ColumnName
When both objects live on the same server you can let the first part away.
Objects of the same database let this part away.
Objects of the default schema might be called with the ObjectName alone.
But if you state a DatabaseName you must also state a SchemaName!
Use QUOTENAME() to add the brackets and add just the dots via string concatenation (or use CONCAT()-function).
UPDATE 2 Did I get this wrong completely?
After you comment I think I understand it now: You want to compare the values of both [USER ID] columns, but the new is DOMAIN\MyUserId while the older was just MyUserId.
You have two approaches
Add the Domain\ as string to the value of [User ID]
Use SUBSTRING([User ID],CHARINDEX('\',[UserID])+1,1000) to cut the newer value down to the naked value of [User ID]
For the first something like this
'WHERE [' + #dest_DB + '].dbo.[' + #dest_table + '].[User ID] = ''' + #domain_name + ''' + src.[User ID]'
The second is quite clumsy with dynamically created SQL...

How to avoid data repetition insertion?

Recently I have posted a question, it contains some syntax error, now the code is running without error, thanks to #Arulkumar.
But now I am facing one more problem, data from excel sheet is storing properly on to SQL Server database, but when I press refresh button or if I go to that link again in my application, data is repeating in the database. Means again it is retrieving values from excel and storing same data again in the database.
How can I avoid data repetition. Can any one please help me to solve this issue? Code and excel sheet sample is there in the above mentioned link.
You need MERGE statement
request.query('MERGE [mytable] as target USING (SELECT SalesPersonID, TerritoryID FROM OPENROWSET(' +
'\'Microsoft.ACE.OLEDB.12.0\', \'Excel 12.0;Database=D:\\sample\\test\\data\\1540_OPENROWSET_Examples.xls;HDR=YES\', ' +
'\'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$]\')' +
' ) as source' +
' ON target.SalesPersonID = source.SalesPersonID' +
' WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +
' WHEN NOT MATCHED THEN INSERT (SalesPersonID, TerritoryID) VALUES (source.SalesPersonID, source.TerritoryID);'
,function(err,recordset){
if(err) console.log(err)
It will update TerritoryID if there is already row with same SalesPersonID and insert row if there is no matches in mytable.
If you need join on both fields change this:
ON target.SalesPersonID = source.SalesPersonID
On this:
ON target.SalesPersonID = source.SalesPersonID AND target.TerritoryID = source.TerritoryID
And after that - remove this string because it doesn't need anymore:
'WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +

SQL limit for XML type

I am actually working on a large database and I am querying the following data;
My Query:
SELECT ldd.LDistCD, ldd.LDistDescPay
FROM LDetail ldd
INNER JOIN LDist ld
ON ldd.ID = ld.ID
AND ld.ID = '019458'
AND ld.LDistType = 'F'
Result:
What I am doing next, is to loop across the results (27873) in my VB codes to concatenate the data in the following format;
LDistCD + '|' + LDistDescPay
Normally that would be a very time consuming time looping through all these rows. Hence to optimise the work, I am using the following query which should already concatenate the data for me;
SELECT stuff((SELECT ',' + ldd.LddLabourDistCD + '|' + ldd.LddLabourDistDescPay
FROM LDetail ldd
INNER JOIN LDist ld
ON ldd.ID = ld.ID
AND ld.ID = 019425 AND ld.LDistType = 'F'
FOR XML
PATH ('')), 1, 1, '')
Everything is working fine except for the result, whereby some data is being truncated!! Running the last query on MS SQL Server returns the concatenate result but it is not complete. I get the impression there's a limit to the result which is being exceeded.
Can anyone help on the issue please?
Difficult for me to upload the db or the result but just to tell you that the 27873 rows, when concatenated in one string, is not fitting in the result.
The truncation you are seeing is specific to SQL Server Management Studio (SSMS). If you go to the Query menu and select Query Options..., then go to Results and then to Grid, you should see on the right side a section for "Maximum Characters Retrieved". The "Non XML data" has a max of 65,535 (which should also be the default) and the "XML data" is a drop-down with options:
1 MB
2 MB (default)
5 MB
Unlimited
Since the XML datatype can bring back more than 65,535 characters, you can convert your output to XML (this is only needed when using SSMS; client libraries should pull back the full string):
SELECT CONVERT(XML,
stuff((SELECT ',' + ldd.LddLabourDistCD + '|' + ldd.LddLabourDistDescPay
FROM LDetail ldd
INNER JOIN LDist ld
ON ldd.ID = ld.ID
AND ld.ID = 019425
AND ld.LDistType = 'F'
FOR XML PATH ('')), 1, 1, '')
)

How to us a LIKE against an IN or list in SQL Server

I have a comma delimited string of keywords which I have successfully transformed into a list using a function that takes a #String and returns a TABLE(Value varchar(30))
I can now use this list in a where clause like follows:
SELECT project.*
FROM Projects project
WHERE project.title IN (SELECT * FROM dbo.ParamsToList('.net,test'))
This matches where project.title is exactly (equal to) any one of the keywords (.net or test).
What I need is to match where title is LIKE '%' + any-keyword + '%'.
One way is like this:
SELECT project.*
FROM Projects project
WHERE EXISTS
(
SELECT * FROM dbo.ParamsToList('.net,test') x
WHERE project.title LIKE '%' + x.value + '%'
)
This approach will mean you don't get the same project returned multiple times, if the project matches multiple values from the params list.
Have you tried JOINING the results of the function like this
SELECT DISTINCT project.*
FROM Projects project
INNER JOIN dbo.ParamsToList('.net,test') pl ON project.title LIKE '%' + pl.Value + '%'

Resources