Retrieve definition of Sequence object in SQL Server - sql

How can I get the definition of any Sequence objects in SQL Server? For instance if I want to get the definition of View/Function/Procedure I would use below query
SELECT OBJECT_DEFINITION(tab.OBJECT_ID)
FROM SYS.OBJECTS tab
WHERE tab.[type] = 'V' /*FOR VIEW*/
SELECT OBJECT_DEFINITION(tab.OBJECT_ID)
FROM SYS.OBJECTS tab
WHERE tab.[type] = 'P' /*FOR PROCEDURE*/
SELECT OBJECT_DEFINITION(tab.OBJECT_ID)
FROM SYS.OBJECTS tab
WHERE tab.[type] = 'TR' /*FOR TRIGGER*/
Please let me know if we have similar options available to get the details for Sequence objects

A SEQUENCE doesn't have the same type of definition as an object like a VIEW or PROCEDURE, however, you could generate your own:
CREATE SEQUENCE dbo.YourSEQUENCE
START WITH 7
INCREMENT BY 4;
GO
SELECT NEXT VALUE FOR dbo.YourSEQUENCE;
GO
SELECT *
FROM sys.sequences
GO
SELECT CONCAT(N'CREATE SEQUENCE ' + QUOTENAME(s.[name]) + N',' + QUOTENAME(sq.[name]),NCHAR(13) + NCHAR(10),
N' START WITH ',CONVERT(int,sq.start_value), NCHAR(13) + NCHAR(10),
N' INCREMENT BY ',CONVERT(int,sq.increment),N';')
FROM sys.schemas s
JOIN sys.sequences sq ON s.schema_id = sq.schema_id
WHERE s.[name] = N'dbo'
AND sq.[name] = N'yourSEQUENCE';
GO
DROP SEQUENCE dbo.YourSEQUENCE;
If this is so you have a repository of all your definitions, that should already be in your Source Control Software.

Your Above Query is right.....
i.e.'V' -- FOR VIEW
'P' -- FOR PROCEDURE
'TR' -- FOR TRIGGER
SELECT sm.object_id, OBJECT_NAME(sm.object_id) AS object_name, o.type, o.type_desc, sm.definition
FROM sys.sql_modules AS sm
JOIN sys.objects AS o ON sm.object_id = o.object_id
ORDER BY o.type;
Use this Query...you will get all the data in single set just refer type Column Name.
Objects of type P, RF, V, TR, FN, IF, TF, and R have an associated SQL
module.
The SQL Server Database Engine assumes that object_id is in the current database context.
The collation of the object definition always matches that of the calling database context.
OBJECT_DEFINITION applies to the following object types:
C = Check constraint
D = Default (constraint or stand-alone)
P = SQL stored procedure
FN = SQL scalar function
R = Rule
RF = Replication filter procedure
TR = SQL trigger (schema-scoped DML trigger, or DDL trigger at either the database or server scope)
IF = SQL inline table-valued function
TF = SQL table-valued function
V = View
For better info ...use this link...
https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-sql-modules-transact-sql?view=sql-server-ver15

Related

Can I check with a T-sql statement if an name is a table/view/storedProcedure/trigger....;

Can I check with a T-sql statement if an name is a table/view/storedProcedure/trigger....;
I want to return 1 row with 2 columns Name, Type.
I know in information_schema.tables, I can find if a Table_Name is a Table or A view. but not if it is a sp or a trigger or a function.
Sys.all_objects table Store every properties you need:
SELECT *
FROM sys.all_objects so
WHERE so.name = 'Something'
type_desc will give you the description of the object type and type is the object type Object type
AGGREGATE_FUNCTION
CHECK_CONSTRAINT
DEFAULT_CONSTRAINT
FOREIGN_KEY_CONSTRAINT
SQL_SCALAR_FUNCTION
CLR_SCALAR_FUNCTION
CLR_TABLE_VALUED_FUNCTION
SQL_INLINE_TABLE_VALUED_FUNCTION
INTERNAL_TABLE
SQL_STORED_PROCEDURE
CLR_STORED_PROCEDURE
PLAN_GUIDE
PRIMARY_KEY_CONSTRAINT
RULE
REPLICATION_FILTER_PROCEDURE
SYSTEM_TABLE
SYNONYM
SERVICE_QUEUE
CLR_TRIGGER
SQL_TABLE_VALUED_FUNCTION
SQL_TRIGGER
TABLE_TYPE
USER_TABLE
UNIQUE_CONSTRAINT
VIEW
EXTENDED_STORED_PROCEDURE
yes, you can use object_id and pass different parameters
for example ,if object_id('tablename','u') checks for users table existence
In information_schema.tables you can find only tables, you have to look for other views like information_schema.views and routines for stored procs
below are total types
AF = Aggregate function (CLR)
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
P = SQL Stored Procedure
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S = System base table
SN = Synonym
SO = Sequence object
Applies to: SQL Server 2012 through SQL Server 2016.
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
TT = Table type
U = Table (user-defined)
UQ = UNIQUE constraint
V = View
X = Extended stored procedure
You can select from DatabaseName.Sys.Objects where Name is like your name for search. Or you can user this syntax:
OBJECT_NAME ( object_id [, database_id ] )
Or in yourdatabasename.sys.all_objects. For example
SELECT *
FROM yourdatabasename.sys.all_objects
WHERE upper(name) like upper('my prefix%')

tSQLt How can I tell if a table has been faked

I am just starting creating some unit tests for my database.
If I have faked a table,
EXEC tSQLt.FakeTable
#TableName = 'dbo.[My Table]',
#Identity = 0,
#ComputedColumns = 0,
#Defaults = 0
Can I check if it has been faked?
Note that documentation on the FakeTable SP can be found here.
Motivation
I want to be able to do this as I imagine creating several stored procedures which populate these faked tables so I can perform tests.
However I do not want to handle faking the tables in the stored procedures (so I can call them multiple times entering different info each time).
I don't want to have the possibility that I forget to fake the table before adding the data (as would almost certainly cause me to fail my test).
tSQLt adds an extended property to a fake table to track the table it fakes. This is easily tested using the function tSQLt.Private_GetOriginalTableName:
SELECT tSQLt.Private_GetOriginalTableName('dbo','[My Table]')
This will return NULL if the table isn't faked.
If you want to do something more complex, you can query sys.extended_properties directly. See the contents of the tSQLt.class.sql script (in the tSQLt distribution) for the definition of tSQLt.Private_GetOriginalTableName.
You can check for the existence of the table at the beginning of your stored procedure(s).
If Not Exists ( Select 1 From Sys.Objects Where [Name] = 'YOURTABLENAME' And [Type] = 'U')
Begin
-- Your Create Table Statement Here
ENd
Based on your comments, the tool has to be doing something like this, using schema:
Create table dbo.MisterPositive ( test int )
Create table developers.MisterPositive (test Int )
-- Both statements below work
Select * From dbo.MisterPositive
Select * From developers.MisterPositive
-- Use this to look for existence prior
Select 1 from sys.objects
Inner join sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
where sys.objects.[Name] = 'MisterPositive' And sys.schemas.name = 'dbo'
Select 1 from sys.objects
Inner join sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
where sys.objects.[Name] = 'MisterPositive' And sys.schemas.name = 'Developers'
So yours would be
If Not Exists ( Select 1 from sys.objects
Inner join sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
where sys.objects.[Name] = 'YOURTABLE' And sys.schemas.[Name] = 'tSQLt' )
Begin
-- create table here
End

Why OBJECT_ID used while checking if a table exists or not

I need to check if a table in SQL exist or not.
If not it must create one automatically.
Now I researched and found this code:
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[YourTable](
....
....
....
)
END
Can anyone explain why it says where object_id = OBJECT_ID and what should I put in its place?
I like this syntax:
if(object_id(N'[dbo].[YourTable]', 'U') is not null)
...
Where object_id takes the 2 char type of object as the second parameter. You can find the list of Object types listed below in the sys.objects documentation:
AF = Aggregate function (CLR)
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
FN = SQL scalar function
FS = Assembly (CLR) scalar-function
FT = Assembly (CLR) table-valued function
IF = SQL inline table-valued function
IT = Internal table
P = SQL Stored Procedure
PC = Assembly (CLR) stored-procedure
PG = Plan guide
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
RF = Replication-filter-procedure
S = System base table
SN = Synonym
SO = Sequence object
SQ = Service queue
TA = Assembly (CLR) DML trigger
TF = SQL table-valued-function
TR = SQL DML trigger
TT = Table type
U = Table (user-defined)
UQ = UNIQUE constraint
V = View
X = Extended stored procedure
The ISO SQL way to check existence of a table level object is the INFORMATION_SCHEMA.TABLES view
There's nothing wrong with looking at sys.objects but.... INFORMATION_SCHEMA.TABLES is a bit more declarative -- and it's cross platform (which often doesn't matter at all but meh still nice.)
I think this is probably more readable for a new coder though:
DECLARE #tableName SYSNAME = 'tbfoo'
DECLARE #schemaNAme SYSNAME = 'fooSchema'
IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = #tableName AND TABLE_SCHEMA = #schemaName )
BEGIN
RAISERROR('%s exists in schema: %s', 0, 1, #tableName, #schemaName)
END
ELSE
BEGIN
RAISERROR('%s DOES NOT EXIST in schema: %s', 0, 1, #tableName, #schemaName)
END
Don't worry about the RAISERROR command -- its just a nice way of printing formatted messages.
You can query the INFORMATION_SCHEMA view to get a sense of what's in it.
SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES
As you can see -- you can reference schemas and catalogs by name rather than looking up their ID with OBJECT_ID()
object_id = OBJECT_ID(N'[dbo].[YourTable]')
object_id is the column name in sys.objects
OBJECT_ID is a function that returns the ID for the object you specify, i.e. YourTable.
You are comparing the object_id of YourTable with the object_id column in the sys.objects table. You need to replace YourTable with the table name you want to check already exists.
OBJECT_ID() is a function which returns the Object ID. See the documentation:
Returns the database object identification number of a schema-scoped
object.
http://msdn.microsoft.com/en-us/library/ms190328.aspx
By passing it certain parameters (ie. your table details), it will return an ID. You can then compare this with the IDs in the sys.objects table to check whether it currently exists.

Find and replace content in stored procedures ms sql server

I want to rename tables and views which are used in stored procedures. Is there any way to find and replace table names in stored procedures, maybe there is tool for ms sql server (i'm using ms sql server 2012).
SQL Server might not allow you to directly UPDATE the object definitions (Views and Stored Proceduress in your case) present in the System catalogs even after setting the 'Allow Updates' option to 1.
The following code will generate the required ALTER Script and you can run them manually after reviewing the definitions ([ModifiedDefinition] )or u can loop through each value of [ModifiedDefinition] and run it using sp_executesql.
SELECT
b.Name AS [ObjectName],
CASE WHEN b.type ='p' THEN 'Stored Procedure'
WHEN b.type ='v' THEN 'View'
ELSE b.TYPE
END AS [ObjectType]
,a.definition AS [Definition]
,Replace ((REPLACE(definition,'OLD Value','New Value')),'Create','ALTER') AS [ModifiedDefinition]
FROM sys.sql_modules a
JOIN
( select type, name,object_id
from sys.objects
where type in (
'p' -- procedures
,'v'--views
)
and is_ms_shipped = 0
)b
ON a.object_id=b.object_id
And as always, be careful with production data and take backups before performing bulk changes on object definitions!!
You can use DBvisualizer .. it pretty much works with all databases and with ms sql too, you can do all you mentioned by using this.
I answered this on another topic (https://stackoverflow.com/a/67728039/11165834) , I do it using the following script:
DECLARE #queryDef NVARCHAR(max)
WHILE EXISTS (
SELECT 1
FROM sys.sql_modules sm
JOIN sys.objects o ON sm.object_id = o.object_id
WHERE sm.definition LIKE '%TEXT_TO_REPLACE%'
AND o.type = 'V'
)
BEGIN
-- TO ALTER THE VIEW AUTOMATICALLY
SET #queryDef = ( SELECT TOP 1 Replace (Replace (sm.definition, 'CREATE VIEW', 'ALTER VIEW'),
'TEXT_TO_REPLACE',
'NEW_TEXT')
FROM sys.sql_modules sm
JOIN sys.objects o ON sm.object_id = o.object_id
WHERE sm.definition LIKE '%TEXT_TO_REPLACE%'
AND o.type = 'V')
EXEC (#queryDef)
END
I use it to replace procedures/views when I restore a backup from production into tests databases.
As #S.A said, be verry careful because is not a verry safe way.
Change the "o.type" and "Replace (sm.definition, 'CREATE VIEW', 'ALTER VIEW'" accordingly to your need

How can I get the 'External name' of a SQL CLR trigger?

I have created a SQL CLR trigger with the follow SQL:
GO
CREATE TRIGGER AuditAccountsTable
ON [dbo].[Accounts]
FOR INSERT,DELETE,UPDATE
AS
EXTERNAL NAME namespace.Triggers.AuditTrigger
I am trying to query:
select * from sys.triggers
Is there a way to find the: EXTERNAL NAME namespace.Triggers.AuditTrigger on the trigger from querying in the DB?
I can't be sure as I don't have a place to test this, but does the text column returned below get you close to what you're looking for?
select t.name, c.text
from sys.triggers t
inner join sys.syscomments c
on t.object_id = c.id
where t.type_desc = 'CLR_TRIGGER'
Unlike T-SQL "modules" such as Stored Procedures and Functions, the SQLCLR T-SQL wrapper objects do not have their CREATE statements stored in the database. This is why you cannot access them via sys.sql_modules, OBJECT_DEFINITION, or the deprecated-since-SQL-Server-2005-and-should-not-be-used sys.syscomments. This is why SQLCLR Stored Procedures and Functions need to have their parameter default values stored in sys.parameters
Instead, CREATE statements for SQLCLR T-SQL wrapper objects are inferred from meta-data, just like Indexes, Primary Keys, Foreign Keys, etc.
You can get all of the parts of the CREATE TRIGGER statement from the following query:
SELECT OBJECT_SCHEMA_NAME(st.[object_id]) AS [SchemaName],
st.[name] AS [TriggerName],
OBJECT_SCHEMA_NAME(st.parent_id) AS [ParentSchemaName],
OBJECT_NAME(st.parent_id) AS [ParentName],
st.is_instead_of_trigger,
SUBSTRING((
SELECT N', ' + ste.[type_desc]
FROM sys.trigger_events ste
WHERE ste.[object_id] = st.[object_id]
FOR XML PATH ('')
), 3, 500) AS [Actions],
QUOTENAME(sa.name) AS [AssemblyName],
QUOTENAME(sam.assembly_class) AS [AssemblyClass],
QUOTENAME(sam.assembly_method) AS [AssemblyMethod]
FROM sys.triggers st
INNER JOIN sys.assembly_modules sam
ON sam.[object_id] = st.[object_id]
INNER JOIN sys.assemblies sa
ON sa.[assembly_id] = sam.[assembly_id]
WHERE st.parent_class = 1; --- OBJECT_OR_COLUMN