SQL SERVER table alias in stored proc - sql

Is there a way to give an alias to a table which will then be referenced within a store procedure.
Declare #target= (sometalbewithveryverylonganduglyname)
Declare #source= (anothertablewithaveryuglyverylongverybadname)
Select * from #target
Insert into #target select from #source
delete from #source
Reason being, the table source and target could change (if the tablename is changed then we just change in one location), and for better readability.

In T-SQL you can't do:
Select * from #target
unless #target is defined as a table-variable, which requires you to set up the table as a user-defined type first. If you're attempting to assign the name of a physical table to the variable and access it this way you'd need to execute the statement using dynamic SQL.
exec ('Select * from #target')
If you just want to alias the table you could write your query like this:
Select * from sometalbewithveryverylonganduglyname AS t
From your question, sounds like the table name can change so you're going to need to use dynamic SQL in the end.

You can't do what you describe unless you resort to dynamic SQL as Yuck suggested, but doing that for the sake of not writing a long table name is not a valid justification. SSMS already includes intellisense and for SQL Server 2005 and below, you can use one of many of the free tools out there. That should reduce the amount of typing that you need to do as well as misspelling mistakes.
Besides, you can always do select t.column1 from really_long_and_ugly_name t ...

option 1) In that case you don't want to use a stored procedure, use some ORM library, it will allow you to switch between different table names with the same structure very easy
option 2) use views, that's what they are for, to hide underlying tables and allow those types of changes

Related

If not exist clause SQL statement

so I found this sql query in a project I am succeeding. This is the first time I encountering this clause/statement. I understand that this is to look if the table exist before creating one and that Object_ID is the table name that is to be created.
My questions are:
Does sysobject mean the database?
What is the Object property?
I know that it is not the columns inside the table to be created.
The columns are : dtb_color_id and description.
can someone explain this to me. please?
IF NOT EXISTS(SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID('DTB_COLOR') AND OBJECTPROPERTY(ID,'ISUserTable') = 1)
BEGIN
.......some query I understand
END
sysobjects, OBJECTPROPERTY and OBJECT_ID are used in Microsoft SQL Server. They are part of the SQL Server DMVs and system functions/procedures used to query and manipulate the metadata.
sys.sysobjects is simply the list of all objects (tables, views, SPs, functions, etc) on the server in the active database. Please note, that sys.sysobjects is deprecated and is only available for backward compatibility. Use sys.objects instead
https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/system-dynamic-management-views?view=sql-server-ver16
It has (as far as I know) no meaning in MySQL, unless somebody specifically created them.
You can also use INFORMATION_SCHEMA which is available in MySQL too (however slightly different in different RDBMS).
MSSQL INFORMATION_SCHEMA: https://learn.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/system-information-schema-views-transact-sql?view=sql-server-ver16
MySQL INFORMATION_SCHEMA: https://dev.mysql.com/doc/refman/8.0/en/information-schema.html
SQL Server has no CREATE TABLE IF NOT EXISTS construct, a variation of the mentioned condition is commonly used to imitate that.
This is a way in SQL Server to check if a table exists in the active database and to perform actions according to the result, like creating the table.
OBJECTPROPERTY simply checks (in this case) if the table is a user created one.
https://learn.microsoft.com/en-us/sql/t-sql/functions/objectproperty-transact-sql?view=sql-server-ver16
I would remove the OBJECTPROPERTY condition in case the part you understand is a CREATE TABLE statement. You don't want to create a table which has a similar name to any system table/view, also you don't want to execute the CREATE TABLE if there is a VIEW with the same name (table creation will fail)
Yes sysobject means database.
The OBJECTPROPERTY() function returns information about schema-
scoped objects in the current database. Use this to check if an
object is a table, view, stored procedure, etc. You can also use
it to check if a table has a primary key, foreign key, foreign
key reference, etc.
For more details : https://learn.microsoft.com/en-us/sql/t-sql/functions/objectpropertyex-transact-sql?view=sql-server-ver16
In this scenario it is used to check whether it is user table or
not. The result of the ISUserTable property is 1 when it is user
table otherwise returns 0.
Here the following steps are followed:
First, it executes the select statement inside the IF Exists
If the select statement returns a value that condition is TRUE for IF Exists
It starts the code inside a begin statement
DTB_COLOR - May be a stored procedure

Query from multiple tables dynamically

I want to query an object from DB that exists in any one of the tables. I am not sure about the table name that a particular object belongs to. For e.g. let's say my DB consists of various tables like Domestic_Passengers, Asian_Passengers, US_Passengers. And this table list may increase as well like in the future we may add the UK_Passengers table too.
So, I want to query something like
SELECT * FROM
(SELECT table_name FROM user_tables where table_name like '%PASSENGER')
WHERE NAME LIKE 'John%'
Is this possible?
That's a very bad database design.
I would suggest a view like this:
CREATE OR REPLACE VIEW PASSENGERS AS
SELECT * FROM Domestic_Passengers
UNION ALL
SELECT * FROM Asian_Passengers
UNION ALL
SELECT * FROM US_Passengers;
And then select from this view.
If this is not possible, then you need to run dynamic SQL in PL/SQL package. But this involves some code.
The best answer depends on a lot of details, such if you can create database objects, how static are the tables, and how will this query be consumed.
If you can create schema objects, and the list of tables is somewhat stable, then Wernfried's answer of building a view is probably best.
If you can create schema objects, but the list of tables is very dynamic, and your application understands ref cursors, you should probably create a function that creates the SELECT and returns it through a ref cursor, like in this answer.
If you cannot create schema objects, then you're limited to the DBMS_XMLGEN/XMLTABLE trick. In a single query, build a string for the SELECT statement you want, run it through DBMS_XMLGEN to create an XMLType, and then use XMLTABLE to transform the XML back into rows and columns. This approach is slow and ugly, but it's the only way to have dynamic SQL in SQL without creating any custom PL/SQL objects. See my answer here for an example.

How to identify all insert calls into a table

I have a table that requires some schema changes which definitely will leave some impact behind especially during Insert. How can I find what are the clients/stored procedure/queries that doing insert into the table and also the related query?
Is this possible to be achieved using SQL Profiler trace?
This will give you the dependent Stored Procedures, Views, Triggers, Functions name on your table.
You need to re-verify once you get the result, whether it is a insert statement or not.
SELECT *
FROM SYS.objects
WHERE OBJECT_DEFINITION(object_id) LIKE '%INSERT%'
AND OBJECT_DEFINITION(object_id) LIKE '%YOUR_TABLE_NME%'
You can change terms in LIKE Operator as per your requirement.
Are you want to find which object is referenced this table?
For sql you can use
SELECT OBJECT_NAME(object_id), * FROM sys.sql_modules WHERE CHARINDEX('mytablename', definition)>0
Or you can download SQL Search

Check if table variable Exists?

Ive searched StackOverFlow , and didnt find any.
Is there any way for me to know if a Table Variable already exists ?
something like :
IF OBJECT_ID('tempdb..#tbl') IS NOT NULL
DROP TABLE #tbl
but for table Var...
Table variables, because they are variables, are distinct from either temporary or non-temporary tables in that they are not created – they are declared. They are much closer in that respect to ‘normal’ variables rather than to tables.
So, there's as much sense in talking about a table variable's existence as in talking about the existence of any variable: if you have declared the thing in your source code, it exists starting from that point until the end of its scope, which, in SQL Server, is known to be either the batch or the stored procedure/function it is declared in. And if you haven't declared the variable and are trying to reference it in your code, your code will just not compile, rendering any existence check pointless, if ever possible.
Perhaps, if you feel the need to drop and re-(create/declare) a table variable in your script, then you should probably consider using a temporary table instead.
Table variables #table are little bit different from temporary tables #table.
Table variables #table need to declare while temporary tables #table should create.
So as per definition declare variables exist between their defined scope (Begin and End) statement. So no need to drop table variables.
But you can use delete #table statement if you want to delete/drop a table variable.
I know this is an old thread, but hopefully this might help someone who lands here. When developing from SSMS, you may want to re-run a statement that selects into a table variable (eg. select * into #tblvarFoo from dbName.schema.Foo). But, the second time you run it, you get an error that it already exists. So, you decide to drop it first. But then, you have the problem the OP had:
Before I drop a table I should check if it exists, otherwise I will
get an exception...
You don't have to drop the table variable or check for its existence.
Just reconnect (right click in the query window and select "Connection->Change Connection...") to same Server/db as before.

MySQL Stored Procedure dynamic change name of table

I wanna change dynamicaly name of table in sql query. For example I have next stored procedure:
CREATE PROCEDURE NewProc(IN tableName varchar(64),IN message text)
BEGIN
INSERT INTO tableName VALUES (message);
END;
I need to change tableName in runtime, Can I to do it or not?
Thanks.
You must use dynamic SQL to prepare and execute an SQL string, to achieve what you describe.
Dynamic table names (or column names, or SQL keywords, etc.) must be interpolated into the SQL string before prepare. You can't use query parameters for these dynamic elements.
Be careful to avoid SQL injection vulnerabilities when you interpolate the table name into your SQL query. For example, you should check that the table name exists by looking it up in the information schema.
I agree with the comment from #OMG Ponies -- it's a code smell that you have multiple tables with identical structure such that you want to do the exact same insert to the exact same column. Code smells aren't a guarantee that you've got a bad design, but it's worth considering.