Determine Tables Referenced By Letters In Stored Procedure - sql-server

I have a stored procedure that references a few tables. However, it refers to the tables with letters.
So let's say a column called Name is from the table Users, then the stored procedure may call the column name U.Users.
My question is, how do I get a list of all such mappings i.e all the letters that map to a table?

you are referring to table aliases, each distinct query can have their own "mapping". These alias values are not specific to stored procedures. Here is an example:
select
a.col1, a.col2
FROM YourTable1 a
select
b.col1, b.col2
from YourTable2 a
inner join YourTable1 b on a.col1=b.col2
YourTable1.col1 and YourTable1.col2 are returned in both of the above queries, although they have the "a" alias in the first query and "b" alias in the second query. See this Using Table Aliases.
In examples like above, people often use a table alias because is is quicker to write a.col1 than YourTable.col1. There is no way for anyone to know the aliases used in your stored procedure, you need to figure that out, look at these examples to help:
FROM YourTable a
-- ^table ^alias
FROM YourTable AS a
-- ^table ^alias
FROM YourTable1 a
INNER JOIN YourTable2 b ON a.col1=b.col1
-- ^table ^alias
FROM YourTable1 AS a
INNER JOIN YourTable2 AS b ON a.col1=b.col1
-- ^table ^alias

Each statement assigns its own aliases for the tables it uses, if at all. The same table used in different statements could be aliased differently (or not aliased). There cannot possibly be a single place to look up every table alias or a simple method to recover them from all the statements in your stored procedure or function or view etc.

Related

SQL table names with spaces

I have a table name with spaces between say like 'Orders Details'.
I want to use that table in stored procedures with joins.I have tried using alias names,[],`` in queries but nothing seems to be working.Can anybody help me on this error!
Do not use order as a column alias. It is a SQL keyword. I would just use o:
select o.*, od.*
from orders o join
order_details od
on o.orderid = od.orderid
where year(o.orderdate) = #orderyear;
Notes:
Your JOIN condition is on ProductId. However, that is highly suspicious. Usually such joins are on the order id. In fact, ProductId doesn't belong in Orders (usually) if there is a detail table.
Do not define your tables with spaces in the name. That just makes it hard to reference the names.
orderdate does not seem to be defined, because it has a red underline.
I don't recommend select *. For one thing, you will have duplicate column names. More importantly, you want to be explicit about what this code returns, particularly in a stored function or procedure.

Find all table column constraints that reference a function

I have multiple tables that use a scalar function in a column's check constraint. Some tables use the same function in more than one column. These constrains obviously all have different names.
I need to alter this function, however first I must remove all constraints that reference it.
Is it possible to get a list of tables and and columns that references this function as a constraint, based on the functions name?
In an ideal world, the name of the constraints would all contain the he name of the function they reference, however unfortunately this is not the case with my database.
you can use this script :
select s.name as constraintName,c.name as ColName,o.name as TableName
from sys.check_constraints s
join sys.all_columns c on s.parent_object_id=c.object_id and s.parent_column_id=c.column_id
join sys.objects o on o.object_id=c.object_id
where s.definition like '%your function name%'

Use result of stored procedure to join to a table

I have a stored procedure that returns a dataset from a dynamic pivot query (meaning the pivot columns aren't know until run-time because they are driven by data).
The first column in this dataset is a product id. I want to join that product id with another product table that has all sorts of other columns that were created at design time.
So, I have a normal table with a product id column and I have a "dynamic" dataset that also has a product id column that I get from calling a stored procedure. How can I inner join those 2?
Dynamic SQL is very powerfull, but has some severe draw backs. One of them is exactly this: You cannot use its result in ad-hoc-SQL.
The only way to get the result of a SP into a table is, to create a table with a fitting schema and use the INSERT INTO NewTbl EXEC... syntax...
But there are other possibilities:
1) Use SELECT ... INTO ... FROM
Within your SP, when the dynamic SQL is executed, you could add INTO NewTbl to your select:
SELECT Col1, Col2, [...] INTO NewTbl FROM ...
This will create a table with the fitting schema automatically.
You might even hand in the name of the new table as a paramter - as it is dynamic SQL, but in this case it will be more difficult to handle the join outside (must be dynamic again).
If you need your SP to return the result, you just add SELECT * FROM NewTbl. This will return the same resultset as before.
Outside your SP you can join this table as any normal table...
BUT, there is a big BUT - ups - this sounds nasty somehow - This will fail, if the tabel exists...
So you have to drop it first, which can lead into deep troubles, if this is a multi-user application with possible concurrencies.
If not: Use IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='NewTbl') DROP TABLE NewTbl;
If yes: Create the table with a name you pass in as parameter and do you external query dynamically with this name.
After this you can re-create this table using the SELECT ... INTO syntax...
2) Use XML
One advantage of XML is the fact, that any structure and any amount of data can be stuffed into one single column.
Let your SP return a table with one single XML column. You can - as you know the schema now - create a table and use INSERT INTO XmlTable EXEC ....
Knowing, that there will be a ProductID-element you can extract this value and create a 2-column-derived-table with the ID and the depending XML. This is easy to join.
Using wildcards in XQuery makes it possible to query XML data without knowing all the details...
3) This was my favourite: Don't use dynamic queries...

SQL Server 2008 insert records then update fields based on another table

In my searches I have found many threads that deal with my issue in round about ways but I have not been able to find one answer that clearly defines the answer.
Yes I'm a noob to SQL Server.
Here is what I am trying to do And I need to know the best way to do it. For the purposes of this question I will keep it simple. Remember it is the functionality I want
I have table A
ClientName,
manager name,
Location
Table B
Manager name
Manager location
Table C
Random columns,
Client name,
Manager name
I want to
take the rows returned from SELECT [client name], [manager name] from table c
Insert those rows into table a with #clientname and #manager name parameters already defined.
Once the row is inserted it will make
tableA.location = Select [manager location]
from tableb
where #manager = tableb.[manager name]
These needs to happen in a batch for multiple rows in one call
This is point in time data so no lookups and no blanket update queries
Use functions?
Stored procedures?
Triggers may not be the answer since I will be inputting 500+ rows on each call
Thank you in advance
It is hard to believe you could not find something very closely related to your question. All you should have to do is
insert TableA
select C.ClientName, C.ManagerName, B.Location
from TableC C
join TableB B on B.ManagerName = C.ManagerName
where C.ManagerName = #ManagerName and C.ClientName = #clientname
Your stated usage case makes this look like you should wrap this inside of a stored proc. In fact, the statement above is the entire body of a stored proc
create proc sotest(#clientname varchar(40), #managername varchar(40)) as
begin
-- code above
end
It is not possible to avoid lookup of location from TableB as your have defined the problem (assuming you want to populated the Location column)

Why the stored procedure needs an alphabet as suffix?

I have a stored Procedure as:
CREATE PROCEDURE [dbo].[spGetEmployeesNotInSkill]
AS
BEGIN
SELECT COUNT (*) as Total FROM
(
SELECT tblUser.EmployeeID FROM tblUser where tblUser.FirstName <> 'guest'
EXCEPT
SELECT tblSkillMetrics.EmployeeID FROM tblSkillMetrics
) r -- why is 'r' used here?
END
What I want to know is why are we using this r? If we change the r to any other letter "a/b/c/...x/y/z" it gives correct output, but if we remove it shows error.
Can anyone please explain this to me?
Whenever you introduce a subquery, CTE, or anything else the will be providing rows as part of a query, you need to provide a name by which that particular set of rows may be referred to elsewhere in the query.
In the case of a table or view, the introduction of an alias is optional, and if omitted, the name of the table or view is used. But for anything else, the name must be explicitly provided.
E.g. you could have had:
SELECT COUNT (*) as Total FROM (
SELECT tblUser.EmployeeID FROM tblUser u where u.FirstName <> 'guest'
EXCEPT
SELECT tblSkillMetrics.EmployeeID FROM tblSkillMetrics)r
Where I've now introduced an alias(u) for tblUser in the inner query. And so in your query, r is the name/alias that's being used for the subquery as a whole.
The r is being used as a table alias. The query is saying "select the number of records in this table that I'm going to call r". So you can call it anything you like.
When you select from a virtual table like this you have to give it an alias - it might be more helpful to call it something like SkilledUsers but as it's only used in one place it's quite common only to use a single character.
It's a quirk of the SQL Server implementation of SQL. The "r" is an alias for the subquery: SQL Server requires that it must be named, even if it is not otherwise referenced. You could just as easily have named it FOO or SUBQUERY or EMPLOYEES.
Other implementations of SQL don't impose this syntactic restriction.
We are using r as an table alias.When u use select * from (select cn from table_name) r you are assigning name r to derived table (select cn from table_name).It will be useful when you are using joins.

Resources