SQL query getting data from 2 different database objects - sql-server

I am very much a beginner at more in depth SQL queries other then simple queries needed to more manage the server side then the database side so any help here is greatly appreciated.
I have a a database for a ticketing system where I need to take data from two different objects and combine the results into the results.
Looks something like this:
+Prof1
- Columns
*AssignedTech (tech assigned task)
*Matters (unique matter ID)
*Type (open, closed, development etc.)
+Matters
- Columns
*MatterNumber
What I am trying to do is get the Matter Number into the query like below but don't know other then perhaps dumping the results to Excel and filtering them from there to get that data into this query. Matters in the DBO corresponds to the unique Matter ID noted above. If i could even run the query below and then use those results to query against the Matters DBO to get the matter ID along with it.
select *
from AssignedTech
where Type like 'open%'
order by Matters

I Believe you want to do is a SQL Join! (I suppose that the Column Matters at Prof1 Table is a reference to the MatterNumber at Matters Table)...
So, to do the join, you must write a query like this:
SELECT A.*, B.MatterNumber
FROM Prof1 A, Matters B
WHERE A.Matters = B.MatterNumber AND A.Type like 'open%'
ORDER BY A.Matters;
Hope this help (also, that I understand you correctly)

Mureinik, I wish I could post a screenshot but hopefully this helps. The section of the DB Basically looks something like this
Example

Related

Most efficient way to view data in table in SQL Server?

Basically if I want to see what the data in a table/view looks like I use
select top 1000 * from ...
But this isn't too efficient for complex views or badly indexed tables.
I really just want to see what the data in a table looks like, e.g. the format etc.
Is there a better way to do this?
I'm using SSMS 2017
*Edit for clarification:
Badly written views are endemic throughout our databases so whilst fixing these is the obvious answer it's not really a realistic one.
I suppose i was hoping for a trick i wasn't aware of, because i understand using TOP puts some sort of order into it
If you highlight a table/view object in code and then press ALT + F1 in SSMS IDE it will execute the equivalent command of sp_help ‘object_name’ where object_name is the name of the highlighted object. Maybe this can give some quick information about the object you are interested in.

Mule - Record cannot be mapped as it contains multiple columns with the same label

I need to do join query to MS SQL Server 2014 DB based on a column name value. The same query runs when doing query directly to DB, but when doing query through Mule I'm getting error. The query looks something like this :
SELECT * FROM sch.emple JOIN sch.dept on sch.emple.empid = sch.dept.empid;
The above query work fine while doing query directly to MS SQL Server DB, but gives the following error through mulesoft.
Record cannot be mapped as it contains multiple columns with the same label. Define column aliases to solve this problem (java.lang.IllegalArgumentException). Message payload is of type: String
Request you to please help me out.
Specify columns list directly:
SELECT e.<col1>, e.<col2>, ...., d.<col1>,...
FROM sch.emple AS e
JOIN sch.dept AS d
ON e.empid = d.empid;
Remarks:
You could use aliases instead of schema.table_name
SELECT * in production code in 95% cases is bad practice
The column that has duplicate is empid(or more). You could add alias for it e.empid AS emple_empid and d.empid AS dept_empid or just specify e.empid once.
To avoid specifying all columns manually, you could drag and drop them from object explorer to query pane like Drag and Drop Column List into query window.
Second way is to use plugin like Redgate Prompt to expand SELECT *:
Image from: https://www.simple-talk.com/sql/sql-tools/sql-server-intellisense-vs.-red-gate-sql-prompt/
Addendum
But the same query works directly.
It works because you don't bind them. Please read carefully link I provided for SELECT * antipattern and especially:
Binding Problems
When you SELECT *, it's possible to retrieve two columns of the same name from two different tables. This can
often crash your data consumer. Imagine a query that joins two
tables, both of which contain a column called "ID". How would a
consumer know which was which? SELECT * can also confuse views (at
least in some versions SQL Server) when underlying table structures
change -- the view is not rebuilt, and the data which comes back can
be nonsense. And the worst part of it is that you can take care
to name your columns whatever you want, but the next guy who comes
along might have no way of knowing that he has to worry about adding a
column which will collide with your already-developed names.
But the same query works directly.
by Dave Markle

query views code (definitions)

I am trying to find some views which have a comment in them - in the code! - (something like '--TO DO'), but the problem is that I don't know the views names and to look at each by hand would take me a whole lot of time (I have over 2k views).
So I am trying to make a query that will search in the view's code for the text of interest.
I managed to come up with something like this:
SELECT *
FROM ALL_SOURCE
WHERE UPPER(text) LIKE UPPER('%my_text_here%')
ORDER BY name desc
But this doesn't query my views. It queries the functions, the procedures, packages, triggers...pretty much everything except the views...which I find pretty odd.
At first I thought that maybe there were no views that contained that keyword so I changed to some basic SQL keywords that I knew for sure exist...and still no results.
Anyone could tell me what am I missing/doing wrong?
Thanks!
The views are stored in all_views (also: dba_views or user_views, depending on your access and needs). However, the text column in all_views is a long, which means you'll first have to convert it to a Clob before you can use it in your query. The easiest work around (from Tom Kyte) would be to create a new table in your schema and convert the Longs into Clobs like this:
create table myviews as
select owner, view_name, to_lob(text) as text from all_views;
Then select from your own table:
select *
from myviews
where upper(text) like upper('%my_text_here%')
order by view_name desc;

Creating SQL Server JSON Parsing/Query UDF

First of all before I get into the question, I'll preface this with the fact that I know that this is a "bad" idea. But for business reasons it is something that I have to come up with a solution to, and I'm hoping that someone, somewhere might have some ideas on how to go about this.
I have a SQL Server 2008 R2 table that has a "OtherProperties" column. This column contains various other, somewhat arbitrary additional pieces of information that relate to the records. There is a business need to create a UDF that we can use to query the results, for example.
SELECT *
FROM MyTable
WHERE MyUDFGetValue(myTable.OtherProperties, "LinkedOrder[0]") IS NOT NULL
This would find a record where there was an array of LinkedOrder entries that contained a value at index 0
SELECT *
FROM MyTable
WHERE MyUDFGetValue(myTable.OtherProperties, "SubOrder.OrderId") = 25
This would find a property "orderId" and use its value in a comparison.
Anyone seen an implementation of this? I've seen implementations of functions. Like this JSONParser that take the values into a table which just will not get us what we need query wise. Complexity wise, I don't want to write a full fledged JSON parser, but I can if I need to.
Not sure if this will suit your needs but I read about a CLR JSON serializer/deserializer. You can find it here, http://www.sqlservercentral.com/articles/CLR/74160/
It's been a long time since you asked your question but there is now a solution you can use - JSON Select which provides various functions for different datatypes, for example the JsonInt() function. From one of your examples (assuming OrderId is an int, if not you could use a different function):
SELECT *
FROM MyTable
WHERE dbo.JsonInt(myTable.OtherProperties, 'SubOrder.OrderId') = 25
DISCLOSURE:
I am the author of JSON Select, and as such have an interest in you using it :)
If you cannot use SQL Server 2016 with built-in JSON support, you would need to use CLR e.g. JSONselect, json4sql, or custom code such as http://www.codeproject.com/Articles/1000953/JSON-for-SQL-Server-Part, etc.

Is it possible to write a database view that encompasses one-to-many relationships?

So I'm not necessarily saying this is even a good idea if it were possible, since the schema of the view would be extremely volatile, but is there any way to represent a has-many relationship in a single view?
For example, let's say I have a customer that can have any number of addresses in the database. Is there any way to list out each column of each address with perhaps a number as a part of the alias (e.g., columns like Customer Id, Name, Address_Street_1, Address_Street_2, etc)?
Thanks!
Not really - you really are doing a dynamic pivot. It's possible to use OPENROWSET to get to a dynamically generated query, but whether that's advisable, it's hard to say without seeing more about the business case.
First make a stored proc which does the dynamic pivot like I did on the StackExchange Data Explorer.
Basically, you generate dynamic SQL which builds the column list. This can only really be done in a stored proc. Which is fine for applciation calls.
But what about if you want to re-use that in a lot of different joins or ad hoc queries?
Then, have a look at this article: "Using SQL Servers OPENROWSET to break the rules"
You can now call your stored proc by looping back into the server and then getting the results into a rowset - this can be in a view!
The late Ken Henderson has some good examples of this in his excellent book: "The Guru's Guide to SQL Server Stored Procedures, XML, and HTML" (you got to love the little "Covers .NET!" on the cover which captures well the zeitgeist for 2002!).
He only covers the loopback part (with views and user-defined functions), the less verbose PIVOT syntax was not available until 2005, but PIVOTs can also be generated using a CASE statement as a characteristic function.
Obviously, this technique has caveats (I can't even do this on our production server).
Yes - use:
CREATE VIEW customer_addresses AS
SELECT t.customer_id,
t.customer_name,
a1.street AS address_street_1,
a2.street AS address_street_2
FROM CUSTOMER t
LEFT JOIN ADDRESS a1 ON a1.customer_id = t.customer_id
LEFT JOIN ADDRESS a2 ON a2.customer_id = t.customer_id
If you provided more info, it'd be easier to give you a better answer. It's possible you're looking to pivot data (turn rows into columns).
Simply put, no. Not without dynamically recreating the view every time you want to use it at least, that is.
But, what you can do is predefine, say, 4 address columns in your view, then populate the first four results of your one-to-many relation into those columns. It's not quite the dynamic view you want, but it's also much more stable/usable in my opinion.

Resources