How to identify all insert calls into a table - sql

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

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.

Using name of a database inside a sql script for a full table name

I struggled for a while with a bug, and then found out the reason for it in a database stored procedure code, which contained the old name of a database in a table name, whereas the current database name was already different. So, I'd like to ask:
Is there a situation in which using a database name as a part of a full table name (database name + schema name + table name) can be justified (provided we don't touch tables in other databases) or is it always a bad practice? How to correctly use a database name in sql scripts to keep code neutral to a specific database?
Code just for an illustration:
CREATE PROCEDURE [dbo].[MyProc]
AS
BEGIN
DELETE FROM [MyDatabase].[dbo].[MyTable]
END
No, you shouldn't use database names in a stored procedure unless you need to address two databases.
It causes exactly the kinds of bugs you're seeing. When the database name changes, all your SP code breaks, or continues working, but on the old database.
It does make sense if you are sending a SQL query to the database, but only if the application dynamically picks the database name to insert into the query.
My suggestion is that you do a full export of your database schema, and search for database names that are hardcoded and remove them.
It really depends on how your scripts are implemented.
Even if you don't refer to a table as
[MyDatabase].[dbo].[MyTable]
you will still need to refer to the database by:
USE [MyDatabase]
earlier in the script.
It is possible to mix trusted database tables in a single query. When someone do this,it is justified and mandatory to include database on table 'path'.
I don't found a reason out of this scenario if stored procedure and table is on the same database.
You can search all database name occurencies through database catalog in order to fix your development. For SQL Server 2005:
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%databasename%'
GO
For SQL Server 2000:
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%databasename%'
GO

SQL SERVER table alias in stored proc

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

creating a table only if it's not existing with ANSI sql

I am trying to dynamically create a SQL table only if it's not already existing. I have seen many solutions on the internet but they usually rely on a specific database, while I'm trying to find the most generic solution.
I was thinking of always running the CREATE command and then assuming that if it fails then the table exist and I can start inserting data into it. I can't see any flaw in this reasoning (not counting performance issues), but I might be wrong.
Is this an acceptable method?
Can you suggest other methods which are database independent, or that use ANSI SQL that all RDBMS would accept?
if there is a table - say - EMP, does that really imply that it is the same EMP that you are expecting?
Either query the appropriate data dictionary for the table structure, or fill your code with a ton of error checking and conditional logic...
INFORMATION_SCHEMA is part of the ANSI SQL Standard, so you should be able to:
IF NOT EXISTS(SELECT NULL FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'YourTable')
CREATE TABLE...
what about: create table if not exists