sql 高级T-SQL脚本(从这里和他们收集)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 高级T-SQL脚本(从这里和他们收集)相关的知识,希望对你有一定的参考价值。


https://www.quora.com/How-do-I-learn-SQL
+
http://www.sql-tutorial.ru/en/content.html
http://www.essentialsql.com/
http://sqlzoo.net/wiki/SQL_Tutorial
+
http://www.java2s.com/Code/SQLServer/CatalogSQLServer.htm
http://www.shikkhok.com/%E0%A6%95%E0%A7%8B%E0%A6%B0%E0%A7%8D%E0%A6%B8-%E0%A6%A4%E0%A6%BE%E0%A6%B2%E0%A6%BF%E0%A6%95%E0%A6%BE/microsoft-sql-server2012/

-------- *** Exploring Your SQL Server Databases with T-SQL *** ---------- 
-- https://www.simple-talk.com/sql/database-administration/exploring-your-sql-server-databases-with-t-sql/


SELECT TOP 10 * FROM [Orders] ORDER BY OrderID DESC



--======================== GET DATABASE AND TABLE INFORMATION =============================

-- GET ALL TABLE AND ALL COLLUMNS OF CURRENT DATABASE
SELECT * FROM INFORMATION_SCHEMA.[COLUMNS] WHERE COLUMN_NAME LIKE '%%'
-- OR (BY Object Name like TableName)
SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo.tbl_user')
-- OR (BY Table Name)
SELECT * FROM AdvancedTSQL.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_user'
-- OR (By GUESSING collumn name)
SELECT top 1 TABLE_NAME FROM INFORMATION_SCHEMA.[COLUMNS] WHERE COLUMN_NAME LIKE '%pass%'



-- Practice to set NOCOUNT ON since SQL Server returns number of rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
SET NOCOUNT ON



-- USEFUL TO GET INFORMATION FROM RUNNING APPLICATION IN LIVE SERVER
SELECT @@VERSION -- Returns current version of the sql server
SELECT @@SERVERNAME --Returns the version of MS SQL Server running on the instance.
SELECT @@SERVICENAME --Returns the name of the MS SQL Server instance.


sp_help TableName

EXEC sp_who
EXEC sp_who2

EXEC sp_helptext sp_who
EXEC sp_helpindex TableName
sp_renamedb 'oldDBName' , 'newDBName'


SP_DEPENDS GenerateStr --SP
sp_help GenerateStr --SP
sp_helptext GenerateStr --SP
SP_DEPENDS AccountInformations --Table




select * from sys.databases
--select * from sysdatabases
Select * from sys.tables
Select * from sys.tables WHERE NAME LIKE '%Product%'
Select * from sys.indexes

Select * from sysindexes 
Select * from sysindexes WHERE NAME LIKE '%Product%'


SELECT * FROM SYSCOLUMNS C 
INNER JOIN SYSOBJECTS O ON C.ID=O.ID
--AND C.NAME LIKE '%id%'


-- GET All Keys of your database
SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE


-- CREATE A NEW TABLE WITH NAME 'TestTable' which is identical to 'Students' table and copy all rows from 'Students' table to 'TestTable'
SELECT * INTO TestTable
FROM Students


----- *** SELECT ALL DATABASE NAMES FROM SQL SERVER
SELECT name
FROM master.dbo.sysdatabases
--OR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
--OR
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
--OR
SELECT * 
FROM sys.databases d
WHERE d.database_id > 4
--OR
SELECT [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 
--OR
SELECT [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'



-- CREATE DATABASE IF NOT EXISTS
IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'RAPIDERP')
DROP DATABASE [RAPIDERP]
GO
CREATE DATABASE RAPIDERP



--** DB BACKUP & RESTORE
-- BACKUP a Database to .bak file
BACKUP DATABASE NORTHWND TO DISK='D:\NORTHWIND.bak'

-- RESTORE .mdf database file from a directory
CREATE DATABASE dbName
ON (FILENAME = 'D:\sk\dbName.mdf')
FOR ATTACH_REBUILD_LOG


-- Get structural information of a table
SP_HELP TableName
--OR
SP_HELP [TableName]



-- SELECT TYPES OF sysobjects 
SELECT DISTINCT XTYPE FROM DBO.SYSOBJECTS


-- ALL USER DEFINED TABLES IN SQL SERVER
SELECT * FROM DBO.SYSOBJECTS WHERE XTYPE = 'U'


-- CONVERT DATETIME string to DateTime
SELECT Convert(datetime, '2010-04-01' )

-- List All Databases
EXEC sp_helpdb;
--OR
EXEC sp_Databases;
--OR
SELECT  @@SERVERNAME AS Server ,
        name AS DBName ,
        recovery_model_Desc AS RecoveryModel ,
        Compatibility_level AS CompatiblityLevel ,
        create_date ,
        state_desc
FROM    sys.databases
ORDER BY Name;
--OR
SELECT  @@SERVERNAME AS Server ,
        d.name AS DBName ,
        create_date ,
        compatibility_level ,
        m.physical_name AS FileName
FROM    sys.databases d
        JOIN sys.master_files m ON d.database_id = m.database_id
WHERE   m.[type] = 0 -- data files only
ORDER BY d.name;
GO









-- Executing a TSQL batch multiple times using GO
INSERT INTO dbo.Students VALUES ('Abull','0202','PK',3)
GO 15

CREATE TABLE dbo.TEST (ID INT IDENTITY (1,1), ROWID uniqueidentifier) 
GO 
INSERT INTO dbo.TEST (ROWID) VALUES (NEWID())  
GO 1000

--Another example
CREATE TABLE dbo.TEST (ID INT IDENTITY (1,1), ROWID uniqueidentifier)  
CREATE TABLE dbo.TEST2 (ID INT IDENTITY (1,1), ROWID uniqueidentifier)  
GO  
INSERT INTO dbo.TEST (ROWID) VALUES (NEWID())  
INSERT INTO dbo.TEST2 (ROWID) VALUES (NEWID())  
GO 1000





-- Listing 1: Basic server information
Select @@SERVERNAME as [Server\Instance]; -- Server and instance name
Select @@VERSION as SQLServerVersion; -- SQL Server Version
Select @@ServiceName AS ServiceInstance; -- SQL Server Instance
Select DB_NAME() AS CurrentDB_Name; -- Current Database





-- Get information of all databases of your sql server
SELECT * FROM sys.databases
SELECT * FROM sys.tables
SELECT * FROM sys.servers





-- Linked Servers
/*Linked Servers are database connections set up to allow communication from SQL Server to other data servers. Distributed queries can be ran against these linked servers. It's good to know if your database server is an isolated self-contained database server or if there are links to other database servers. */
EXEC sp_linkedservers;
EXEC sp_helpserver;



-- check dependencies of a table in sql server


-- Listing 2: how long has your server been running since startup?
-- Note the tempdb system database is recreated every time the server restarts
-- Thus this is one method to tell when the database server was last restarted
SELECT  @@Servername AS ServerName ,
        create_date AS ServerStarted ,
        DATEDIFF(s, create_date, GETDATE()) / 86400.0 AS DaysRunning ,
        DATEDIFF(s, create_date, GETDATE()) AS SecondsRunnig
FROM    sys.databases
WHERE   name = 'tempdb';
GO






-- SEE WHICH DATABASE BACKUP has Taken Already
SELECT  @@Servername AS ServerName ,
        d.Name AS DBName ,
        MAX(b.backup_finish_date) AS LastBackupCompleted
FROM    sys.databases d
        LEFT OUTER JOIN msdb..backupset b
                    ON b.database_name = d.name
                       AND b.[type] = 'D'
GROUP BY d.Name
ORDER BY d.Name;



--  Physical file location for recent backups
SELECT  @@Servername AS ServerName ,
        d.Name AS DBName ,
        b.Backup_finish_date ,
        bmf.Physical_Device_name
FROM    sys.databases d
        INNER JOIN msdb..backupset b ON b.database_name = d.name
                                        AND b.[type] = 'D'
        INNER JOIN msdb.dbo.backupmediafamily bmf ON b.media_set_id = bmf.media_set_id
ORDER BY d.NAME ,
        b.Backup_finish_date DESC;
GO






-- Listing out all user-defined tables in a database
USE NORTHWND;
GO
SELECT  *
FROM    sys.objects
WHERE   type = 'U';



-- Database File Location: Physical location and drive of the current database file, including the master database file (*.mdf) and the Log database file (*.ldf) can be found using these queries.
EXEC sp_Helpfile;
--OR
SELECT  @@Servername AS Server ,
        DB_NAME() AS DB_Name ,
        File_id ,
        Type_desc ,
        Name ,
        LEFT(Physical_Name, 1) AS Drive ,
        Physical_Name ,
        RIGHT(physical_name, 3) AS Ext ,
        Size ,
        Growth
FROM    sys.database_files
ORDER BY File_id;
GO


-- Listing 13: Return table row counts from the index or table partition
-- Get row count of each individual tables with a t-sql query
SELECT
      QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName]
      , SUM(sPTN.Rows) AS [RowCount]
FROM 
      sys.objects AS sOBJ
      INNER JOIN sys.partitions AS sPTN
            ON sOBJ.object_id = sPTN.object_id
WHERE
      sOBJ.type = 'U'
      AND sOBJ.is_ms_shipped = 0x0
      AND index_id < 2 -- 0:Heap, 1:Clustered
GROUP BY 
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [TableName]
GO



-- A faster way to get table row counts.
-- Hint: get it from an index, not the table.
SELECT  @@ServerName AS Server ,
        DB_NAME() AS DBName ,
        OBJECT_SCHEMA_NAME(p.object_id) AS SchemaName ,
        OBJECT_NAME(p.object_id) AS TableName ,
        i.Type_Desc ,
        i.Name AS IndexUsedForCounts ,
        SUM(p.Rows) AS Rows
FROM    sys.partitions p
        JOIN sys.indexes i ON i.object_id = p.object_id
                              AND i.index_id = p.index_id
WHERE   i.type_desc IN ( 'CLUSTERED', 'HEAP' )
                             -- This is key (1 index per table)
        AND OBJECT_SCHEMA_NAME(p.object_id) <> 'sys'
GROUP BY p.object_id ,
        i.type_desc ,
        i.Name
ORDER BY SchemaName ,
        TableName;
 
-- OR
-- Similar method to get row counts, but this uses DMV dm_db_partition_stats
SELECT  @@ServerName AS ServerName ,
        DB_NAME() AS DBName ,
        OBJECT_SCHEMA_NAME(ddps.object_id) AS SchemaName ,
        OBJECT_NAME(ddps.object_id) AS TableName ,
        i.Type_Desc ,
        i.Name AS IndexUsedForCounts ,
        SUM(ddps.row_count) AS Rows
FROM    sys.dm_db_partition_stats ddps
        JOIN sys.indexes i ON i.object_id = ddps.object_id
                              AND i.index_id = ddps.index_id
WHERE   i.type_desc IN ( 'CLUSTERED', 'HEAP' )
                              -- This is key (1 index per table)
        AND OBJECT_SCHEMA_NAME(ddps.object_id) <> 'sys'
GROUP BY ddps.object_id ,
        i.type_desc ,
        i.Name
ORDER BY SchemaName ,
        TableName;
GO










-- Finding Heaps (tables with no clustered index) 
-- Working with heap tables is like working with a flat file, instead of a database. If you want to guarantee a full table scan for any and all queries, use a heap table. My general recommendation would be to add a primary key clustered index to all heap tables.
-- Heap tables (Method 1)
SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DBName ,
        t.Name AS HeapTable ,
        t.Create_Date
FROM    sys.tables t
        INNER JOIN sys.indexes i ON t.object_id = i.object_id
                                    AND i.type_desc = 'HEAP'
ORDER BY t.Name
--OR
-- Heap tables (Method 2)
SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DBName ,
        t.Name AS HeapTable ,
        t.Create_Date
FROM    sys.tables t
WHERE   OBJECTPROPERTY(OBJECT_ID, 'TableHasClustIndex') = 0
ORDER BY t.Name;
--OR
-- Heap tables (Method 3) also provides row counts
SELECT  @@ServerName AS Server ,
        DB_NAME() AS DBName ,
        OBJECT_SCHEMA_NAME(ddps.object_id) AS SchemaName ,
        OBJECT_NAME(ddps.object_id) AS TableName ,
        i.Type_Desc ,
        SUM(ddps.row_count) AS Rows
FROM    sys.dm_db_partition_stats AS ddps
        JOIN sys.indexes i ON i.object_id = ddps.object_id
                              AND i.index_id = ddps.index_id
WHERE   i.type_desc = 'HEAP'
        AND OBJECT_SCHEMA_NAME(ddps.object_id) <> 'sys'
GROUP BY ddps.object_id ,
        i.type_desc
ORDER BY TableName;



-- Identity Column:  IDENTITY columns are populated with unique system controlled numbers. A common example is an order number, where each time an order is entered into the system, SQL Server assigns to the IDENTITY column the next sequential number.

SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DBName ,
        OBJECT_SCHEMA_NAME(object_id) AS SchemaName ,
        OBJECT_NAME(object_id) AS TableName ,
        Column_id ,
        Name AS IdentityColumn ,
        Seed_Value ,
        Last_Value
FROM    sys.identity_columns
ORDER BY SchemaName ,
        TableName ,
        Column_id;
GO


-- Keys and Indexes: As discussed earlier, a general best practice all tables should have a primary key clustered index. As a second general best practice, foreign keys should have a supporting index on the same columns as the foreign key. Foreign key indexes provide the most likely way that tables be joined together in multi-table queries. Foreign key indexes are also important for performance when deleting records.
-- What indexes exist?
-- To see which indexes exist on all tables in the current database.

SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DB_Name ,
        o.Name AS TableName ,
        i.Name AS IndexName
FROM    sys.objects o
        INNER JOIN sys.indexes i ON o.object_id = i.object_id
WHERE   o.Type = 'U' -- User table
        AND LEFT(i.Name, 1) <> '_' -- Remove hypothetical indexes
ORDER BY o.NAME ,
        i.name;
GO




-- Foreign Keys: Foreign Keys define table dependencies and control referential integrity between multiple tables. In an Entity Relationship Diagram (ERD), the lines between the tables indicate the foreign keys.
-- Foreign Keys
SELECT  @@Servername AS ServerName ,
        DB_NAME() AS DB_Name ,
        parent.name AS 'TableName' ,
        o.name AS 'ForeignKey' ,
        o.[Type] ,
        o.Create_date
FROM    sys.objects o
        INNER JOIN sys.objects parent ON o.parent_object_id = parent.object_id
WHERE   o.[Type] = 'F' -- Foreign Keys
ORDER BY parent.name ,
        o.name
--OR
SELECT  f.name AS ForeignKey ,
        SCHEMA_NAME(f.SCHEMA_ID) AS SchemaName ,
        OBJECT_NAME(f.parent_object_id) AS TableName ,
        COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName ,
        SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName ,
        OBJECT_NAME(f.referenced_object_id) AS ReferenceTableName ,
        COL_NAME(fc.referenced_object_id, fc.referenced_column_id)
                                              AS ReferenceColumnName
FROM    sys.foreign_keys AS f
        INNER JOIN sys.foreign_key_columns AS fc
               ON f.OBJECT_ID = fc.constraint_object_id
        INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
ORDER BY TableName ,
        ReferenceTableName;
GO






-- Using a Common Table Expression (CTE): The third method to reverse engineer your database hierarchical dependencies is to solve a recursive query using a Common Table Expression (CTE).
-- How to find the hierarchical dependencies
-- Solve recursive queries using Common Table Expressions (CTE)
WITH    TableHierarchy ( ParentTable, DependentTable, Level )
          AS (
-- Anchor member definition (First level group to start the process)
               SELECT DISTINCT
                        CAST(NULL AS INT) AS ParentTable ,
                        e.referenced_object_id AS DependentTable ,
                        0 AS Level
               FROM     sys.foreign_key_columns AS e
               WHERE    e.referenced_object_id NOT IN (
                        SELECT  parent_object_id
                        FROM    sys.foreign_key_columns )
-- Add filter dependents of only one parent table
-- AND Object_Name(e.referenced_object_id) = 'User'
               UNION ALL
-- Recursive member definition (Find all the layers of dependents)
               SELECT --Distinct
                        e.referenced_object_id AS ParentTable ,
                        e.parent_object_id AS DependentTable ,
                        Level + 1
               FROM     sys.foreign_key_columns AS e
                        INNER JOIN TableHierarchy AS d
                               ON ( e.referenced_object_id ) = 
                                                      d.DependentTable
             )
    -- Statement that executes the CTE
SELECT DISTINCT
        OBJECT_NAME(ParentTable) AS ParentTable ,
        OBJECT_NAME(DependentTable) AS DependentTable ,
        Level
FROM    TableHierarchy
ORDER BY Level ,
        ParentTable ,
        DependentTable;
		
		
		
		


-- create database if not exist
USE master
IF EXISTS (SELECT * FROM sys.tables WHERE name like '%RAPIDERP%')
DROP DATABASE [RAPIDERP]
GO
CREATE DATABASE [RAPIDERP]
GO







--=========================== DECLARE VARIABLE AND SET AGGREGATE VALUE TO THAT VARIABLE =====================

DECLARE @AverageAge as int = 0
UPDATE tbl_student SET @AverageAge += Age
select @AverageAge


DECLARE @AverageAge as int = 0, @RowCount int
UPDATE tbl_student SET @AverageAge += Age+1
set @RowCount = (select count(*) from tbl_student)
select @AverageAge/@RowCount as 'Average Age'


declare @TotalAge int
set @TotalAge=(select sum(age) from tbl_student)
select @TotalAge as 'Total Age'




--============================ BATCH INSERT ===============================
CREATE TABLE [dbo].[Demodata]
(
    [ID] INT NOT NULL PRIMARY KEY IDENTITY(1,1), 
    [Name] VARCHAR(150) NULL, 
    [Price] VARCHAR(150) NULL
)

DECLARE @id int = 1
DECLARE @price int = 100
WHILE  @id>=1 and @id<=10000
BEGIN
INSERT INTO Demodata VALUES ('Test Name '+ CONVERT(VARCHAR(50),@id)  ,@price+@id)
SET @id+=1
END






----------- add foreign key constraints-----------
SELECT * FROM [dbo].[SAL_Order]
SELECT * FROM [dbo].[SAL_OrderDetail]

ALTER TABLE [SAL_OrderDetail]
ADD CONSTRAINT fk_OrderDetailOrderID
FOREIGN KEY (OrderID)
REFERENCES [SAL_Order](OrderID)





SELECT * FROM Students 
select @@rowcount as 'RowCount'




--=================== REMOVE all data from your DATABASE ( keeping existing foreign key constraints [FK] ) ======================
http://stackoverflow.com/questions/3687575/delete-all-data-in-sql-server-database
-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
GO 
EXEC sp_MSForEachTable 'DELETE FROM ?' 
GO 
-- enable referential integrity again 
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL' 
GO
-- RESET Identity Seed for all table of your database
EXEC sp_MSforeachtable 'DBCC CHECKIDENT ([?], reseed, 0)'





--===================== DROP all tables from a Database ==============================
http://stackoverflow.com/questions/8439650/how-to-drop-all-tables-in-a-database
-- select a database first, otherwise something bad could happen, like all tables from all of your sql server databse can be deleted!!!! 
EXEC sp_msforeachtable 'drop table [?]'




--==================== Display total number of rows for each table in selected database ===========
-- http://www.besttechtools.com/articles/article/sql-query-to-display-total-number-of-rows-for-each-table
select o.name 'Table Name',rowcnt 'Total Number of Rows' from sysindexes i
inner join  sysobjects o on i.id=o.id
where indid<2
and o.xtype='U'
Order by 'Total Number of Rows' DESC





--============== GET Any Username and Password by just guessing table name, username field and password field ==============
DECLARE @tableName NVARCHAR(50)
SET @tableName = 'dbo.tbl_user'
DECLARE @userFieldName NVARCHAR(50)
SET @userFieldName = 'user'
DECLARE @passwordFieldName NVARCHAR(50)
SET @passwordFieldName = 'pass'
DECLARE @tmpU NVARCHAR(250)
DECLARE @tmpP NVARCHAR(250)
DECLARE @sqlCommand NVARCHAR(MAX)
SET @tmpU = (SELECT top 1 name FROM sys.columns WHERE object_id = OBJECT_ID(@tableName) AND NAME LIKE '%'+@userFieldName+'%')
SET @tmpP = (SELECT top 1 name FROM sys.columns WHERE object_id = OBJECT_ID(@tableName) AND NAME LIKE '%'+@passwordFieldName+'%');
--PRINT @tableName+'='+@tmpU+'='+@tmpP
--SELECT * FROM tbl_user  WHERE UserName = (SELECT TOP 1 UserName FROM tbl_user)
SET @sqlCommand = 'SELECT * FROM '+@tableName+' WHERE '+@tmpU+'=(SELECT TOP 1 '+@tmpU+' FROM '+@tableName+');';
EXEC (@sqlCommand)



-- THIS ONE IS MUCH MORE DYNAMIC THAN PREVIOUS
DECLARE @guessPassField NVARCHAR(50)
SET @guessPassField = '%pass%'
DECLARE @guessUserField NVARCHAR(50)
SET @guessUserField = '%user%'
DECLARE @tableName NVARCHAR(50)
SET @tableName = (SELECT top 1 TABLE_NAME FROM INFORMATION_SCHEMA.[COLUMNS] WHERE COLUMN_NAME LIKE @guessPassField)
DECLARE @userFieldName NVARCHAR(50)
SET @userFieldName = (SELECT top 1 COLUMN_NAME FROM INFORMATION_SCHEMA.[COLUMNS] WHERE COLUMN_NAME LIKE @guessUserField AND TABLE_NAME = @tableName)
DECLARE @passwordFieldName NVARCHAR(50)
SET @passwordFieldName = (SELECT top 1 COLUMN_NAME FROM INFORMATION_SCHEMA.[COLUMNS] WHERE COLUMN_NAME LIKE @guessPassField AND TABLE_NAME = @tableName)
DECLARE @sqlCommand NVARCHAR(MAX)
SET @sqlCommand = 'SELECT * FROM '+@tableName+' WHERE '+@userFieldName+'=(SELECT TOP 1 '+@userFieldName+' FROM '+@tableName+');';
EXEC (@sqlCommand)









-- Query to get field name with datatype and size
SELECT column_name as 'Column Name', data_type as 'Data Type',
character_maximum_length as 'Max Length'
FROM information_schema.columns
WHERE table_name = 'tbl_student' 






-- Clearing Down A Database Full Of Constraints In SQL Server
-- http://www.c-sharpcorner.com/blogs/clearing-down-a-database-full-of-constraints-in-sql-server
USE dRetail;   
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"   
EXEC sp_MSForEachTable "DELETE FROM ?"   
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"   
GO   






-- Get Latest Executed Queries In SQL Server
SELECT  
deqs.last_execution_time AS [Time],   
dest.TEXT AS [Query]  
FROM   
sys.dm_exec_query_stats AS deqs  
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest  
ORDER BY   
deqs.last_execution_time DESC   





-- Generate Random Password Using SQL Stored Procedure
CREATE PROCEDURE GENERATEPWD(@OUTMESSAGE VARCHAR(10) OUTPUT)  
AS   
BEGIN  
SET NOCOUNT ON  
declare @LENGTH INT,@CharPool varchar(26),@PoolLength varchar(26),@LoopCount  INT  
DECLARE @RandomString VARCHAR(10),@CHARPOOLINT VARCHAR(9)  
  
SET @CharPool = 'A!B@C!D#E@FG#H$IJ$K%LM%N*PQR%ST&U*V(W)X_YZ'  
DECLARE @TMPSTR VARCHAR(3)  

SET @PoolLength = DataLength(@CharPool)  
SET @LoopCount = 0  
SET @RandomString = ''  
  
    WHILE (@LoopCount <10)  
    BEGIN  
        SET @TMPSTR =   SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength), 1)           
        SELECT @RandomString  = @RandomString + CONVERT(VARCHAR(5), CONVERT(INT, RAND() * 10))  
        IF(DATALENGTH(@TMPSTR) > 0)  
        BEGIN   
            SELECT @RandomString = @RandomString + @TMPSTR    
            SELECT @LoopCount = @LoopCount + 1  
        END  
    END  
    SET @LOOPCOUNT = 0    
    SET @OUTMESSAGE=@RandomString  
END  






-- List of Primary Key and Foreign Key for Whole Database
SELECT DISTINCT  
Constraint_Name AS [Constraint],    
Table_Schema AS [Schema],  
Table_Name AS [TableName] 
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE


-- Search Through List of Primary Key and Foreign Key from Whole Database
SELECT * FROM
(
	SELECT DISTINCT  
	Constraint_Name AS [Constraint],    
	Table_Schema AS [Schema],  
	Table_Name AS [TableName] 
	FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
) result
where [Constraint] like '%Users%'







--  GET List Schema Name and Table Name for Database
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
AS SchemaTable
FROM sys.tables





--====================== FIND STRING IN A TABLE =========================
--EXEC FindStringInTable '%s%', 'dbo', 'tbl_student'
CREATE PROCEDURE [dbo].[FindStringInTable] 
@stringToFind VARCHAR(100), 
@schema sysname='dbo',
@table sysname 
AS

BEGIN TRY
   DECLARE @sqlCommand varchar(max) = 'SELECT * FROM [' + @schema + '].[' + @table + '] WHERE ' 
	   
   SELECT @sqlCommand = @sqlCommand + '[' + COLUMN_NAME + '] LIKE ''%' + @stringToFind + '%'' OR '
   FROM INFORMATION_SCHEMA.COLUMNS 
   WHERE TABLE_SCHEMA = @schema
   AND TABLE_NAME = @table 
   AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')

   SET @sqlCommand = left(@sqlCommand,len(@sqlCommand)-3)
   EXEC (@sqlCommand)
   PRINT @sqlCommand
END TRY

BEGIN CATCH 
   PRINT 'There was an error. Check to make sure object exists.'
   PRINT error_message()
END CATCH




--==================== CHECK if Stored Procedure Exists or not ========================
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'P' and name = 'Notifications')
BEGIN
print 'sp already exists'
DROP PROCEDURE Notifications
END
else print 'SP does not exists'






------------------ SPLIT COMMA SEPARATED STRINGS INTO ROWS -----------------------
-- EXAMPLE INPUT : '30027,30034,30035'
-- EXAMPLE OUTPUT: 
--Column1
--30027
--30034
--30035
CREATE FUNCTION dbo.BreakStringIntoRows (@CommadelimitedString   varchar(1000))
RETURNS   @Result TABLE (Column1   VARCHAR(100))
AS
BEGIN
      DECLARE @IntLocation INT
      WHILE (CHARINDEX(',',    @CommadelimitedString, 0) > 0)
      BEGIN
            SET @IntLocation =   CHARINDEX(',',    @CommadelimitedString, 0)      
            INSERT INTO   @Result (Column1)
            --LTRIM and RTRIM to ensure blank spaces are   removed
            SELECT RTRIM(LTRIM(SUBSTRING(@CommadelimitedString,   0, @IntLocation)))   
            SET @CommadelimitedString = STUFF(@CommadelimitedString,   1, @IntLocation,   '') 
      END
      INSERT INTO   @Result (Column1)
      SELECT RTRIM(LTRIM(@CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed
      RETURN 
END
GO

-- EXAMPLE:
SELECT Column1 FROM dbo.BreakStringIntoRows('30027,30034,30035')






--============================ STRING TO ROWS (Utility Function) ==================================
CREATE FUNCTION StringToRows(@str VARCHAR(MAX))
RETURNS @names TABLE(Name VARCHAR(255))
AS 
BEGIN 
    WHILE (CHARINDEX(',', @str) > 0)
    BEGIN
        INSERT INTO @names VALUES(SUBSTRING(@str, 1, CHARINDEX(',', @str) - 1))
        SET  @str = SUBSTRING(@str, CHARINDEX(',', @str) + 1, 100)  
    END
    INSERT INTO @names VALUES(@str)  
    RETURN
END


SELECT * FROM StringToRows('Abul,Kabul,Dabul,Rahul,Kobir,Jordan Mollick,Hasibul Haque');







--============================ Custom Shortcut For Quick Table Data ================================
--EXAMPLE 1::::::
IF (OBJECT_ID('spCustomShortcutsForQuickTableData') IS NOT NULL) DROP PROCEDURE spCustomShortcutsForQuickTableData
GO
CREATE PROC spCustomShortcutsForQuickTableData ( @tableName NVARCHAR(128) )
AS
BEGIN
    DECLARE @str NVARCHAR(MAX);
    SET @str = N'SELECT TOP 200 * FROM '+@tableName;
    EXEC sp_executesql @str
END

-- CALL IT BY CHANGING TableName and Number of Rows you want to be returned
EXEC spCustomShortcutsForQuickTableData 'Roles'


-- Go TO....
-- SSMS Menu >> Tools >> Options >> Environment >> Keyboard >> Query Shortcuts.
-- and set the name of this SP their
-- now in query window write and select the table name and press that shortcut and you will get top 1 result








--============================ CHECKING IF EXISTS =============================
-- CHECK IF StoredProcedure Exists:
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'P' and name = 'Notifications')
BEGIN
   DROP PROCEDURE Notifications
END
GO 

-- CHECK IF Temp Table Exists:
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp;
GO
CREATE TABLE #tmp ([Key] varchar(200), [Value] int);
GO


-- CREATE DATABASE IF NOT EXISTS
IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'RAPIDERP')
DROP DATABASE [RAPIDERP]
GO
CREATE DATABASE RAPIDERP


-- CHECKING IF DATABASE EXISTS
USE master
IF EXISTS (SELECT * FROM sys.tables WHERE name like '%RAPIDERP%')
DROP DATABASE [RAPIDERP]
GO
CREATE DATABASE [RAPIDERP]
GO


-- CHECKING IF StoredProcedure exists
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'P' and name = 'Notifications')
BEGIN
print 'sp already exists'
DROP PROCEDURE Notifications
END
else print 'SP does not exists'



-- CHECKING IF TempTable Exists
IF OBJECT_ID('tempdb..#Notification') IS NOT NULL 
    DROP TABLE #Notification;
CREATE TABLE #Notification ([Key] varchar(200), [Value] int, [Module] varchar(max),  [SubModule] varchar(max), [Status] varchar(max));


-- CHECK IF Function Exists
IF EXISTS (
    SELECT * FROM dbo.sysobjects 
    WHERE id = object_id(N'[dbo].[BreakStringIntoRows]')
    AND xtype IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[BreakStringIntoRows] 
--PRINT 'FUNCTION EXIST!'
ELSE 
BEGIN 
    PRINT 'Function Doesn''t Exists' 
END




--================= All xtypes of SQL Server object Types / listing of sysobjects.xtype descriptions  ========================
-- http://stackoverflow.com/questions/16243857/is-there-a-table-that-holds-the-listing-of-sysobjects-xtype-descriptions
SELECT name  FROM master..spt_values 
WHERE type = 'O9T'

/*
| xtype |              Description              |
|-------|---------------------------------------|
| AF    |  Aggregate function (CLR)             |
| C     |  CHECK constraint                     |
| D     |  Default or DEFAULT constraint        |
| F     |  FOREIGN KEY constraint               |
| L     |  Log                                  |
| FN    |  Scalar function                      |
| FS    |  Assembly (CLR) scalar-function       |
| FT    |  Assembly (CLR) table-valued function |
| IF    |  In-lined table-function              |
| IT    |  Internal table                       |
| P     |  Stored procedure                     |
| PC    |  Assembly (CLR) stored-procedure      |
| PK    |  PRIMARY KEY constraint (type is K)   |
| RF    |  Replication filter stored procedure  |
| S     |  System table                         |
| SN    |  Synonym                              |
| SQ    |  Service queue                        |
| TA    |  Assembly (CLR) DML trigger           |
| TF    |  Table function                       |
| TR    |  SQL DML Trigger                      |
| TT    |  Table type                           |
| U     |  User table                           |
| UQ    |  UNIQUE constraint (type is K)        |
| V     |  View                                 |
| X     |  Extended stored procedure            |
*/

---------AND----------

    --AF: aggregate function
    --AP: application
    --C : check cns
    --D : default (maybe cns)
    --EN: event notification
    --F : foreign key cns
    --FN: scalar function
    --FS: assembly scalar function
    --FT: assembly table function
    --IF: inline function
    --IS: inline scalar function
    --IT: internal table
    --L : log
    --P : stored procedure
    --PC : assembly stored procedure
    --PK: primary key cns
    --R : rule
    --RF: replication filter proc
    --S : system table
    --SN: synonym
    --SO: sequence object
    --SQ: queue
    --TA: assembly trigger
    --TF: table function
    --TR: trigger
    --U : user table
    --UQ: unique key cns
    --V : view
    --X : extended stored proc
    --sysobjects.type, reports


--select object_name(c.id), c.name, [length], o.xtype from syscolumns c
--    join sysobjects o on o.id = c.id
--where c.name like '%job%code%'


--select object_name(c.id), c.name, t.name, c.[length], o.xtype, x.name from syscolumns c
--    join sysobjects o on o.id = c.id
--    join systypes t on t.xtype = c.xtype
--    join master..spt_values x on x.name like '%' + o.xtype + '%' and x.type = 'O9T'
--where c.name like '%job%code%'
--order by c.xtype






-- ============================= SEE WHATS RUNNING ON Your SQL SERVER =================================
-- An enhanced way to see what active queries are running on a database instance
CREATE PROCEDURE sp_whatsRunning
(
    @SessionID int = NULL
)
AS
BEGIN
SELECT
    SPID                = er.session_id
    ,Status             = ses.status
    ,[Login]            = ses.login_name
    ,Host               = ses.host_name
    ,BlkBy              = er.blocking_session_id
    ,DBName             = DB_Name(er.database_id)
    ,CommandType        = er.command
    ,SQLStatement       =  
                    SUBSTRING 
                    (
                    qt.text,
                    er.statement_start_offset/2,
                    (CASE WHEN er.statement_end_offset = -1
                        THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
                        ELSE er.statement_end_offset
                        END - er.statement_start_offset)/2
                    )
    ,ObjectName         = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid)
    ,ElapsedMS          = er.total_elapsed_time
    ,CPUTime            = er.cpu_time
    ,IOReads            = er.logical_reads + er.reads
    ,IOWrites           = er.writes
    ,LastWaitType       = er.last_wait_type
    ,StartTime          = er.start_time
    ,Protocol           = con.net_transport
    ,transaction_isolation = CASE ses.transaction_isolation_level
                    WHEN 0 THEN 'Unspecified'
                    WHEN 1 THEN 'Read Uncommitted'
                    WHEN 2 THEN 'Read Committed'
                    WHEN 3 THEN 'Repeatable'
                    WHEN 4 THEN 'Serializable'
                    WHEN 5 THEN 'Snapshot'
                END
    ,ConnectionWrites   = con.num_writes
    ,ConnectionReads    = con.num_reads
    ,ClientAddress      = con.client_net_address
    ,Authentication     = con.auth_scheme
    
    FROM sys.dm_exec_requests er
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
    LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
    CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
    WHERE @SessionID IS NULL OR er.session_id = @SessionID
    AND er.session_id > 50
    ORDER BY er.blocking_session_id DESC,er.session_id
END


-- TEST: EXEC sp_whatsRunning






--*** ======================== SEE ALL TABLES And Their Row Count / Data Count of your database ========================= *** 
SELECT so.name as TableName, MAX(si.rows) as [RowCount] 
FROM sysobjects so
JOIN sysindexes si ON si.id = OBJECT_ID(so.name)
WHERE so.xtype = 'U'
GROUP BY so.name 
ORDER BY [RowCount] DESC

-- SEE TotalRowCount of all tables of your database
SELECT SUM([RowCount]) as TotalRows FROM (
SELECT so.name as TableName, MAX(si.rows) as [RowCount] 
FROM sysobjects so
JOIN sysindexes si ON si.id = OBJECT_ID(so.name)
WHERE so.xtype = 'U'
GROUP BY so.name 
) X






-------------------- Use this Query to Find FKs that aren't named after their table:   ------------------------
-- misnamed sql server foreign key query (FK-validation.sql) 
-- GitHub Gist: https://gist.github.com/timabell/d017038af96196b84e56
SELECT obj.name, fk.name
FROM SYS.FOREIGN_KEYS fk
inner join SYS.OBJECTS obj ON obj.object_id = fk.parent_object_id
WHERE fk.name not like 'FK_' + obj.name + '_%'  -- -- use this where clause to find FKs that aren't named after their table:
ORDER BY obj.name, fk.name





---------- FIND ALL TABLE'S COLUMN AND THEIR TYPES, Nullability, PK/FK etc... ---------------------
SELECT obj.name [Table], col.name [Attribute], typ.name [DataType], col.isnullable [Allow Nulls?],
CASE WHEN d.name is null THEN 0
    ELSE 1 END [PKey?],
CASE WHEN e.parent_object_id is null THEN 0
    ELSE 1 END [FKey?],
CASE WHEN e.parent_object_id is null THEN '-'
    ELSE g.name END [Ref Table],
CASE WHEN h.value is null THEN '-' ELSE h.value
    END [Description]
FROM sysobjects AS obj
JOIN syscolumns AS col ON obj.id = col.id
JOIN systypes AS typ ON col.xtype = typ.xtype
LEFT JOIN (
      SELECT  so.id,sc.colid,sc.name
      FROM    syscolumns sc
      JOIN sysobjects so ON so.id = sc.id
      JOIN sysindexkeys si ON so.id = si.id AND sc.colid = si.colid
      WHERE si.indid = 1
      ) d on obj.id = d.id and col.colid = d.colid
LEFT JOIN sys.foreign_key_columns AS e
    ON obj.id = e.parent_object_id AND col.colid = e.parent_column_id   
LEFT JOIN sys.objects as g
    ON e.referenced_object_id = g.object_id 
LEFT JOIN sys.extended_properties AS h
    ON obj.id = h.major_id AND col.colid = h.minor_id
WHERE obj.type = 'U' ORDER BY obj.name






--======================= INSERT RESULTS OF A STORED PROCEDURE INTO A TEMPORARY TABLE =================================
--------- WAY 1::: DECLARING Temp Table Structure First --------------
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp;
CREATE TABLE #tmp (
    Name varchar(255), 
    Reg varchar(255), 
    [Address] varchar(255)
);
--INSERT @tempTable  EXEC spStudentsBasicInfo;
INSERT INTO #tmp EXEC spStudentsBasicInfo
SELECT * FROM #tmp



------------ WAY-2:: (USING Table Variable) --------------
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL  DROP TABLE #tmp;
DECLARE @tempTable TABLE (
    name VARCHAR(255),
    reg VARCHAR(255),
    [address] VARCHAR(255)
);
INSERT @tempTable  EXEC spStudentsBasicInfo;
--select * from @tempTable;

SELECT * INTO #tmp FROM @tempTable
SELECT * FROM #tmp






--=================== GET All StoredProcedure Names and Their Number of Lines =====================
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp;
CREATE TABLE #tmp (
    SPName varchar(100), 
    Lines int
);
--INSERT INTO #tmp Values('AAAA' ,44)

SET NOCOUNT ON
DECLARE @ProcName varchar(100)
DECLARE @LineCount int
DECLARE C CURSOR LOCAL FOR
    SELECT o.name as ProcName FROM sysobjects o WHERE (o.xtype = 'P') ORDER BY o.name
OPEN C
CREATE TABLE #ProcLines ([Text] varchar(1000))
FETCH NEXT FROM C INTO @ProcName
WHILE @@FETCH_STATUS = 0 
BEGIN
    DELETE FROM #ProcLines
    INSERT INTO #ProcLines EXEC('sp_helptext ' + @ProcName + '')
    SELECT @LineCount = COUNT(*) FROM #ProcLines
        PRINT @ProcName + '   Lines: ' + LTRIM(STR(@LineCount))
        INSERT INTO #tmp Values(@ProcName ,@LineCount)
    FETCH NEXT FROM C INTO @ProcName
END
CLOSE C
DEALLOCATE C
DROP TABLE #ProcLines


SELECT * FROM #tmp ORDER BY Lines DESC






--================ GET ALL TABLES AND THEIR Number Of Rows ==========================
SELECT  SUBSTRING(obj.name, 1, 50) AS Table_Name
        ,ind.rows AS Number_of_Rows
FROM    sysobjects AS obj
INNER JOIN sysindexes AS ind ON obj.id = ind.id
WHERE   obj.xtype = 'U'
        AND ind.indid < 2
        AND ind.rows > 0
ORDER BY obj.name






------------------- SQL Server Version ---------------
SELECT @@microsoftversion/ 0x01000000 as VersionNumber, @@version VersionText

SELECT 
CASE @@microsoftversion/ 0x01000000 
    WHEN 6 THEN 'You''ve got to be kidding me.'
    WHEN 7 THEN 'SQL Server 7.0'
    WHEN 8 THEN 'SQL Server 2000'
    WHEN 9 THEN 'SQL Server 2005'
    WHEN 10 THEN 'SQL Server 2008'
    WHEN 11 THEN 'SQL Server 2012'
    WHEN 12 THEN 'Time to update your gist, homey.'
    WHEN 13 THEN 'SQL Server 2016'
END




----------------- GET DATE / DATE FORMATTER / GET SYSTEM DATE --------------------
SELECT TOP 1 GETDATE() 'Default',
     CONVERT(varchar,GETDATE(),108) 'hh:mm:ss',
     CONVERT(varchar,GETDATE(),114) 'hh:mm:ss:mmm',
     CONVERT(varchar,GETDATE(),113) 'dd Mmm yyyy hh:mm:ss:mmm'
 GO




--========================== GENERATE C# CLASS/MODEL AUTO PROPERTIES FROM A TABLE ========================
-- Generates a POCO (plain old C# object) based on the table/view schema in SQL Server.
-- https://gist.github.com/pdwetz/491e8a0478c2e2f7ba0a2acd5839c497
declare @table varchar(50);
set @table = 'tbl_student';

select 'public ' + tps.dest
+ (case when IS_NULLABLE = 'YES' and tps.dest != 'string' then '? ' else ' ' end)
+ column_name + ' { get; set; }' AS 'C# Class Properties / POCO'
from information_schema.columns c
  join (
    select 'char' as origin, 'string' as dest union all
    select 'varchar', 'string' union all
    select 'nvarchar', 'string' union all
    select 'text', 'string' union all
    select 'binary', 'byte[]' union all
    select 'uniqueidentifier', 'Guid' union all
    select 'datetime', 'DateTime' union all
    select 'date', 'DateTime' union all
    select 'int', 'int' union all
    select 'decimal', 'decimal' union all
    select 'float', 'float' union all
    select 'bit', 'bool'
  ) tps on c.DATA_TYPE like tps.origin
where table_name = @table





--============================== CONVERT ALL VARCHAR COLUMN(n) TO NVARCHAR(n) TYPE (for any Database) ===============================
-- ex: ALTER TABLE dbo.[tbl_student]  ALTER COLUMN [name] NVARCHAR(50)  NULL;

/**
 * Creates a list of statements to convert all varchar columns to nvarchar.
 * Those statements can then be copied and executed in order to actually convert your tables.
 *
 * NOTE: Indexes and Foreign Keys must be dropped and recreated before and after
 * convertion execution.
 * @see: (Drop and create indexes)[https://gist.github.com/erremauro/8defeb747f02c59560b6]
 * @see: (Drop and create foreign keys)[https://gist.github.com/erremauro/4c7ff9cdd8c1eb044ea3]
 *
 * @author: Roberto Mauro<erremauro@icloud.com>
 * @platform: SQL Server
 */
SELECT 'ALTER TABLE ' + ISNULL(schema_name(syo.id), 'dbo') + '.[' +  syo.name +'] ' 
+ ' ALTER COLUMN [' + syc.name + '] NVARCHAR(' + 
CASE syc.length 
  when -1 then 'MAX'
  /**
   * VARCHAR as a max of 8000 characters while NVARCHAR, 
   * using double of the space, results in 4000 characters max. 
   */
  when 8000 then '4000'
ELSE 
  convert(nvarchar(10),syc.length)
END + ') '+ 
CASE  syc.isnullable 
  when 1 then ' NULL' 
ELSE 
  ' NOT NULL' 
END +';'
FROM sysobjects syo 
JOIN syscolumns syc ON syc.id = syo.id 
JOIN systypes syt ON syt.xtype = syc.xtype 
WHERE syt.name = 'varchar' 
AND syo.xtype='U'






-- RETRIEVE Table Information using Query
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Employee'





--=========================  CREATE A Blank Same Table Structure from an existing table (without copying table data) =====================
SELECT * INTO tbl_student_copy FROM tbl_student WHERE 1<>1
SELECT * INTO tbl_student_copy FROM tbl_student WHERE 1=2
SELECT TOP 0 * INTO tbl_student_copy FROM tbl_student

-- IF Source and Destination Database are different
Select * INTO AdvancedTSQL.dbo.MenuConfigs_Copy from FinCrime.dbo.MenuConfigs
Select * INTO MenuConfigs_Copy from FinCrime.dbo.MenuConfigs WHERE 1<>1
Select * INTO AdvancedTSQL.dbo.MenuConfigs_Copy from FinCrime.dbo.MenuConfigs WHERE 1<>1






--==================== BULK INSERT Data INTO Table Variables and Select from them ========================
-- EXAMPLE 1:
DECLARE @tblVariable TABLE (Id INT PRIMARY KEY, Name NVARCHAR(MAX), Reg NVARCHAR(20))
INSERT INTO @tblVariable 
SELECT Id, Name, Reg FROM tbl_student
SELECT * FROM @tblVariable


DECLARE @tblVariable TABLE (Id INT PRIMARY KEY, Name NVARCHAR(MAX), Reg NVARCHAR(20))
INSERT @tblVariable 
SELECT Id, Name, Reg FROM tbl_student
SELECT * FROM @tblVariable





-- ===================== FIND ALL TABLES AND There RowCount Ordered by RowCount ===================
SELECT * FROM 
(
    SELECT  [Tables].name AS [TableName], SUM([Partitions].[rows]) AS [TotalRowCount]
    FROM    sys.tables AS [Tables]
    JOIN    sys.partitions AS [Partitions]
    ON      [Tables].[object_id] = [Partitions].[object_id]
    AND [Partitions].index_id IN (0,1)
    --WHERE    [Tables].name = N'table name' /* uncomment to look for a specific table */
    GROUP BY    [Tables].name
) rs
ORDER BY TotalRowCount DESC






-- ############=============== Search and Return All Tables and Columns Containing a Specified Column Value  ===========##########
-- http://stackoverflow.com/documentation/sql-server/697/retrieve-information-about-the-database#t=201704151010401868737
-- See more at: http://thesitedoctor.co.uk/blog/search-every-table-and-field-in-a-sql-server-database-updated#sthash.bBEqfJVZ.dpuf

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT


DECLARE @SearchStr nvarchar(100)
SET @SearchStr = 'Sheikh' 
    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
    SET NOCOUNT ON
 
    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
    WHILE @TableName IS NOT NULL
    BEGIN
        SET @ColumnName = ''
        SET @TableName =
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE  TABLE_TYPE = 'BASE TABLE'
                   AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                   AND    OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
        )
 
        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                      AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                      AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                      AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )
     
            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END   
    END
 
    SELECT ColumnName, ColumnValue FROM #Results
DROP TABLE #Results

















--######################## Get the list of all databases on a server ####################   
-- Method 1: Below query will be applicable for SQL Server 2000+ version (Contains 12 columns)
SELECT * FROM dbo.sysdatabases

-- Method 2: Below query extract information about databases with more informations (ex: State, Isolation, recovery model etc.)
SELECT * FROM sys.databases

-- Method 3: To see just database names you can use undocumented sp_MSForEachDB
EXEC sp_MSForEachDB 'SELECT ''?'' AS DatabaseName'

-- Method 4: Below SP will help you to provide database size along with databases name , owner, status etc. on the server
EXEC sp_helpdb

-- Method 5 Similarly, below stored procedure will give database name, database size and Remarks
EXEC sp_databases





--######################## Retrieve a List of all Stored Procedures ####################
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'


SELECT *
FROM sys.objects
WHERE type = 'P'


SELECT *
FROM sysobjects
WHERE type = 'P'




--######################## Count the Number of Tables in a Database ####################
-- This query will return the number of tables in the specified database.
SELECT COUNT(*) FROM sys.tables

-- OR
USE AdvancedTSQL
SELECT COUNT(*) from INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' 




--######################## Find All Database Files of This Database Server ####################
--######################## Display all data files for all databases with size and growth info ####################
SELECT  d.name AS 'Database',
        d.database_id,  
        SF.fileid,
        SF.name AS 'LogicalFileName',   
        CASE SF.status & 0x100000  
            WHEN 1048576 THEN 'Percentage' 
            WHEN 0 THEN 'MB' 
        END AS 'FileGrowthOption',
        Growth AS GrowthUnit,
        ROUND(((CAST(Size AS FLOAT)*8)/1024)/1024,2) [SizeGB], -- Convert 8k pages to GB
        Maxsize,        
        filename AS PhysicalFileName

FROM    Master.SYS.SYSALTFILES SF
Join    Master.SYS.Databases d on sf.fileid = d.database_id
Order by d.name





--######################## Find every mention of a field in the database ####################
SELECT DISTINCT
 o.name AS Object_Name,o.type_desc
 FROM sys.sql_modules m 
    INNER JOIN sys.objects  o ON m.object_id=o.object_id
 WHERE m.definition Like '%Name%'
 ORDER BY 2,1




-- **********######################## Get all schemas, tables, columns and indexes ####################************
SELECT 
    s.name AS [schema],
    t.object_id AS [table_object_id], 
    t.name AS [table_name],
    c.column_id,
    c.name AS [column_name],
    i.name AS [index_name],
    i.type_desc AS [index_type]
FROM sys.schemas AS s
INNER JOIN sys.tables AS t 
    ON s.schema_id = t.schema_id
INNER JOIN sys.columns AS c 
    ON t.object_id = c.object_id
LEFT JOIN sys.index_columns AS ic 
    ON c.object_id = ic.object_id and c.column_id = ic.column_id
LEFT JOIN sys.indexes AS i 
    ON ic.object_id = i.object_id and ic.index_id = i.index_id
ORDER BY [schema], [table_name], c.column_id;




--######################## Retrieve Database Options ####################
select * from sys.databases WHERE name = 'AdvancedTSQL';





--######################## Retrieve Tables Containing Known Column ####################
-- This query will return all COLUMNS and their associated TABLES for a given column name. 
-- It is designed to show you what tables (unknown) contain a specified column (known)
SELECT 
    c.name AS ColName, 
    t.name AS TableName
FROM 
    sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE 
    c.name LIKE '%Name%'






--######################## See if Enterprise-specific features are being used ####################
SELECT * FROM sys.dm_db_persisted_sku_features






--######################## Show Size of All Tables in Current Database ####################
SELECT
    s.name + '.' + t.NAME AS TableName,
    SUM(a.used_pages)*8 AS 'TableSizeKB'  --a page in SQL Server is 8kb
FROM sys.tables t
    JOIN sys.schemas s on t.schema_id = s.schema_id
    LEFT JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
    LEFT JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
    LEFT JOIN sys.allocation_units a ON p.partition_id = a.container_id
GROUP BY
    s.name, t.name
ORDER BY
    --Either sort by name:
    s.name + '.' + t.NAME
    --Or sort largest to smallest:
    --SUM(a.used_pages) desc






--######################## Retrieve information on backup and restore operations ####################
-- EXAMPLE 1:
SELECT 
    [d].[name] AS database_name, 
    [r].restore_date AS last_restore_date, 
    [r].[user_name], 
    [bs].[backup_finish_date] AS backup_creation_date, 
    [bmf].[physical_device_name] AS [backup_file_used_for_restore] 
FROM master.sys.databases [d] 
    LEFT OUTER JOIN msdb.dbo.[restorehistory] r ON r.[destination_database_name] = d.Name 
    INNER JOIN msdb.dbo.backupset [bs] ON [r].[backup_set_id] = [bs].[backup_set_id] 
    INNER JOIN msdb.dbo.backupmediafamily bmf ON [bs].[media_set_id] = [bmf].[media_set_id] 
ORDER BY [d].[name], [r].restore_date DESC



-- EXAMPLE 2:
SELECT sdb.Name AS DatabaseName,
    COALESCE(CONVERT(VARCHAR(50), bus.backup_finish_date, 120),'-') AS LastBackUpDateTime
FROM sys.sysdatabases sdb
    LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
ORDER BY sdb.name, bus.backup_finish_date DESC






--######################## Return a list of SQL Agent jobs, with schedule information ####################

USE msdb
Go

SELECT dbo.sysjobs.Name AS 'Job Name', 
      'Job Enabled' = CASE dbo.sysjobs.Enabled
            WHEN 1 THEN 'Yes'
            WHEN 0 THEN 'No'
      END,
      'Frequency' = CASE dbo.sysschedules.freq_type
            WHEN 1 THEN 'Once'
            WHEN 4 THEN 'Daily'
            WHEN 8 THEN 'Weekly'
            WHEN 16 THEN 'Monthly'
            WHEN 32 THEN 'Monthly relative'
            WHEN 64 THEN 'When SQLServer Agent starts'
      END, 
      'Start Date' = CASE active_start_date
            WHEN 0 THEN null
            ELSE
            substring(convert(varchar(15),active_start_date),1,4) + '/' + 
            substring(convert(varchar(15),active_start_date),5,2) + '/' + 
            substring(convert(varchar(15),active_start_date),7,2)
      END,
      'Start Time' = CASE len(active_start_time)
            WHEN 1 THEN cast('00:00:0' + right(active_start_time,2) as char(8))
            WHEN 2 THEN cast('00:00:' + right(active_start_time,2) as char(8))
            WHEN 3 THEN cast('00:0' 
                        + Left(right(active_start_time,3),1)  
                        +':' + right(active_start_time,2) as char (8))
            WHEN 4 THEN cast('00:' 
                        + Left(right(active_start_time,4),2)  
                        +':' + right(active_start_time,2) as char (8))
            WHEN 5 THEN cast('0' 
                        + Left(right(active_start_time,5),1) 
                        +':' + Left(right(active_start_time,4),2)  
                        +':' + right(active_start_time,2) as char (8))
            WHEN 6 THEN cast(Left(right(active_start_time,6),2) 
                        +':' + Left(right(active_start_time,4),2)  
                        +':' + right(active_start_time,2) as char (8))
      END,

      CASE len(run_duration)
            WHEN 1 THEN cast('00:00:0'
                        + cast(run_duration as char) as char (8))
            WHEN 2 THEN cast('00:00:'
                        + cast(run_duration as char) as char (8))
            WHEN 3 THEN cast('00:0' 
                        + Left(right(run_duration,3),1)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 4 THEN cast('00:' 
                        + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 5 THEN cast('0' 
                        + Left(right(run_duration,5),1) 
                        +':' + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 6 THEN cast(Left(right(run_duration,6),2) 
                        +':' + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
      END as 'Max Duration',
    CASE(dbo.sysschedules.freq_subday_interval)
            WHEN 0 THEN 'Once'
            ELSE cast('Every ' 
                        + right(dbo.sysschedules.freq_subday_interval,2) 
                        + ' '
                        +     CASE(dbo.sysschedules.freq_subday_type)
                                          WHEN 1 THEN 'Once'
                                          WHEN 4 THEN 'Minutes'
                                          WHEN 8 THEN 'Hours'
                                    END as char(16))
    END as 'Subday Frequency'
FROM dbo.sysjobs 
LEFT OUTER JOIN dbo.sysjobschedules 
ON dbo.sysjobs.job_id = dbo.sysjobschedules.job_id
INNER JOIN dbo.sysschedules ON dbo.sysjobschedules.schedule_id = dbo.sysschedules.schedule_id 
LEFT OUTER JOIN (SELECT job_id, max(run_duration) AS run_duration
            FROM dbo.sysjobhistory
            GROUP BY job_id) Q1
ON dbo.sysjobs.job_id = Q1.job_id
WHERE Next_run_time = 0

UNION

SELECT dbo.sysjobs.Name AS 'Job Name', 
      'Job Enabled' = CASE dbo.sysjobs.Enabled
            WHEN 1 THEN 'Yes'
            WHEN 0 THEN 'No'
      END,
      'Frequency' = CASE dbo.sysschedules.freq_type
            WHEN 1 THEN 'Once'
            WHEN 4 THEN 'Daily'
            WHEN 8 THEN 'Weekly'
            WHEN 16 THEN 'Monthly'
            WHEN 32 THEN 'Monthly relative'
            WHEN 64 THEN 'When SQLServer Agent starts'
      END, 
      'Start Date' = CASE next_run_date
            WHEN 0 THEN null
            ELSE
            substring(convert(varchar(15),next_run_date),1,4) + '/' + 
            substring(convert(varchar(15),next_run_date),5,2) + '/' + 
            substring(convert(varchar(15),next_run_date),7,2)
      END,
      'Start Time' = CASE len(next_run_time)
            WHEN 1 THEN cast('00:00:0' + right(next_run_time,2) as char(8))
            WHEN 2 THEN cast('00:00:' + right(next_run_time,2) as char(8))
            WHEN 3 THEN cast('00:0' 
                        + Left(right(next_run_time,3),1)  
                        +':' + right(next_run_time,2) as char (8))
            WHEN 4 THEN cast('00:' 
                        + Left(right(next_run_time,4),2)  
                        +':' + right(next_run_time,2) as char (8))
            WHEN 5 THEN cast('0' + Left(right(next_run_time,5),1) 
                        +':' + Left(right(next_run_time,4),2)  
                        +':' + right(next_run_time,2) as char (8))
            WHEN 6 THEN cast(Left(right(next_run_time,6),2) 
                        +':' + Left(right(next_run_time,4),2)  
                        +':' + right(next_run_time,2) as char (8))
      END,

      CASE len(run_duration)
            WHEN 1 THEN cast('00:00:0'
                        + cast(run_duration as char) as char (8))
            WHEN 2 THEN cast('00:00:'
                        + cast(run_duration as char) as char (8))
            WHEN 3 THEN cast('00:0' 
                        + Left(right(run_duration,3),1)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 4 THEN cast('00:' 
                        + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 5 THEN cast('0' 
                        + Left(right(run_duration,5),1) 
                        +':' + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
            WHEN 6 THEN cast(Left(right(run_duration,6),2) 
                        +':' + Left(right(run_duration,4),2)  
                        +':' + right(run_duration,2) as char (8))
      END as 'Max Duration',
    CASE(dbo.sysschedules.freq_subday_interval)
            WHEN 0 THEN 'Once'
            ELSE cast('Every ' 
                        + right(dbo.sysschedules.freq_subday_interval,2) 
                        + ' '
                        +     CASE(dbo.sysschedules.freq_subday_type)
                                          WHEN 1 THEN 'Once'
                                          WHEN 4 THEN 'Minutes'
                                          WHEN 8 THEN 'Hours'
                                    END as char(16))
    END as 'Subday Frequency'
FROM dbo.sysjobs 
LEFT OUTER JOIN dbo.sysjobschedules ON dbo.sysjobs.job_id = dbo.sysjobschedules.job_id
INNER JOIN dbo.sysschedules ON dbo.sysjobschedules.schedule_id = dbo.sysschedules.schedule_id 
LEFT OUTER JOIN (SELECT job_id, max(run_duration) AS run_duration
            FROM dbo.sysjobhistory
            GROUP BY job_id) Q1
ON dbo.sysjobs.job_id = Q1.job_id
WHERE Next_run_time <> 0

ORDER BY [Start Date],[Start Time]











--=================================== *** ORDER BY COLUMN Name - ASC/DESC *** =========================
DECLARE @QUERY VARCHAR(2000)
DECLARE @TABLENAME VARCHAR(50) = 'CustomerDynamicInformations'

SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + Column_name + ', 
'
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_NAME = @TABLENAME
  ORDER BY Column_name

SET @QUERY =  LEFT(@QUERY, LEN(@QUERY) - 4) + ' 
FROM '+ @TABLENAME
--PRINT @QUERY
EXEC(@QUERY)






--===============  Exclude a column from Select List (SELECT * [except columnA] FROM tableA) =====================
-- EXAMPLE 1:
SELECT * INTO #TempTable FROM CustomerInformations
ALTER TABLE #TempTable DROP COLUMN Id, BranchId, CustomerNo
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable



-- EXAMPLE 2:
DECLARE @cols VARCHAR(max), @query VARCHAR(max);
SELECT  @cols = STUFF
    (
        ( 
            SELECT DISTINCT '], [' + name
            FROM sys.columns
            where object_id = (
                select top 1 object_id from sys.objects
                where name = 'tbl_student'
            )
            and name not in ('Id', 'Name')
            FOR XML PATH('')
        ), 1, 2, ''
    ) + ']';
SELECT @query = 'select ' + @cols + ' from tbl_student';  
EXEC (@query);








/*
-- =============================================
-- Author     : Kawser Sheikh
-- Create date: 04-25-2017
-- Description:  IF are trying to print a very large text, then you might encounter TRUNCATION of text in the output window, 
     So, in that case this StoredProcedure might be useful to print long text
-- =============================================
*/
SET NOCOUNT ON
IF OBJECT_ID('dbo.usp_PrintBig') IS NOT NULL
  DROP PROCEDURE dbo.usp_PrintBig
GO

--EXEC usp_PrintBig @dynamicSQL
CREATE PROCEDURE dbo.usp_PrintBig (
   @text NVARCHAR(MAX)
 )
AS
--DECLARE @text NVARCHAR(MAX) = 'YourTextHere'
DECLARE @lineSep NVARCHAR(2) = CHAR(13) + CHAR(10)  -- Windows \r\n
 
DECLARE @off INT = 1
DECLARE @maxLen INT = 4000
DECLARE @len INT
 
WHILE @off < LEN(@text)
BEGIN
 
  SELECT @len =
    CASE
      WHEN LEN(@text) - @off - 1 <= @maxLen THEN LEN(@text)
      ELSE @maxLen
             - CHARINDEX(REVERSE(@lineSep),  REVERSE(SUBSTRING(@text, @off, @maxLen)))
             - LEN(@lineSep)
             + 1
    END
  PRINT SUBSTRING(@text, @off, @len)
  --PRINT '@off=' + CAST(@off AS VARCHAR) + ' @len=' + CAST(@len AS VARCHAR)
  SET @off += @len + LEN(@lineSep)
END
GO





-- #####################################################################################################################
-- ======== [SOverflow Question] : GET ALL COLLUMN FROM A JOINED QUERY, SEARCH IN COLUMN NAME AND SORT THEM!! ==========
-- #####################################################################################################################

-- EXAMPLE 1:
DECLARE @QUERY VARCHAR(2000)
DECLARE @TABLENAME1 VARCHAR(100) = 'CustomerInformations'
DECLARE @TABLENAME2 VARCHAR(100) = 'CustomerDynamicInformations'

SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + TABLE_NAME + '.' + COLUMN_NAME + ', 
'
 FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE (TABLE_NAME = @TABLENAME1
 OR TABLE_NAME = @TABLENAME2)
 AND COLUMN_NAME LIKE '%nid%'
 ORDER BY Column_name

SET @QUERY =  LEFT(@QUERY, LEN(@QUERY) - 4) + ' 
FROM '+ @TABLENAME1 + ' INNER JOIN '+ @TABLENAME2 +
' ON '+@TABLENAME1 + '.CustomerDynamicInfoId='+@TABLENAME2+'.Id'
PRINT @QUERY
EXEC(@QUERY)



-- EXAMPLE 2 (BEST):
------------------ FIX IT (LATER)------------- IT WILL BE MUCH MORE DYNAMIC
DECLARE @query VARCHAR(2000)
DECLARE @columnNameLike VARCHAR(100) = '%ACC%'
DECLARE @tbl1 VARCHAR(100) = 'CustomerInformations'
DECLARE @tbl1JoinColumn VARCHAR(100) = 'CustomerDynamicInfoId'

DECLARE @tbl2 VARCHAR(100) = 'CustomerDynamicInformations'
DECLARE @tbl2JoinColumn VARCHAR(100) = 'Id'

SET @query = 'SELECT '
SELECT @query = @query + TABLE_NAME + '.' + COLUMN_NAME + ', 
'
 FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE (TABLE_NAME = @tbl1 OR TABLE_NAME = @tbl2)
 AND COLUMN_NAME LIKE @columnNameLike
 ORDER BY COLUMN_NAME

SET @query =  LEFT(@query, LEN(@query) - 4) + ' 
FROM '+ @tbl1 + ' INNER JOIN '+ @tbl2 +
' ON ' +@tbl1 + '.'+@tbl1JoinColumn + '='+@tbl2+'.'+@tbl2JoinColumn

PRINT @query
EXEC(@query)




-- EXAMPLE 3:
------------------ WORKING SOMEWHAT...
DECLARE @QUERY VARCHAR(2000)
DECLARE @TABLENAME1 VARCHAR(100) = 'CustomerInformations'
DECLARE @TABLENAME2 VARCHAR(100) = 'CustomerDynamicInformations'

SET @QUERY = 'SELECT '
SELECT @QUERY = @QUERY + TABLE_NAME + '.' + COLUMN_NAME + ', 
'
 FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE (TABLE_NAME = @TABLENAME1
 OR TABLE_NAME = @TABLENAME2)
 AND COLUMN_NAME LIKE '%nid%'
 ORDER BY Column_name

SET @QUERY =  LEFT(@QUERY, LEN(@QUERY) - 4) + ' 
FROM '+ @TABLENAME1 + ' INNER JOIN '+ @TABLENAME2 +
' ON '+@TABLENAME1 + '.CustomerDynamicInfoId='+@TABLENAME2+'.Id'
PRINT @QUERY
EXEC(@QUERY)





-- EXAMPLE 4:
-- OR CAN USE LIKE THIS
BEGIN TRY
    DECLARE @query VARCHAR(2000)
  DECLARE @columnNameLike VARCHAR(100) = '%ACC%'
  DECLARE @tbl1 VARCHAR(100) = 'CustomerInformations'
  DECLARE @tbl1JoinColumn VARCHAR(100) = 'CustomerDynamicInfoId'

  DECLARE @tbl2 VARCHAR(100) = 'CustomerDynamicInformations'
  DECLARE @tbl2JoinColumn VARCHAR(100) = 'Id'

  SET @query = 'SELECT '
  SELECT @query = @query + TABLE_NAME + '.' + COLUMN_NAME + ', 
  '
   FROM INFORMATION_SCHEMA.COLUMNS 
   WHERE (TABLE_NAME = @tbl1 OR TABLE_NAME = @tbl2)
   AND COLUMN_NAME LIKE @columnNameLike
   ORDER BY COLUMN_NAME

  SET @query =  LEFT(@query, LEN(@query) - 4) + ' 
  FROM '+ @tbl1 + ' INNER JOIN '+ @tbl2 +
  ' ON ' +@tbl1 + '.'+@tbl1JoinColumn + '='+@tbl2+'.'+@tbl2JoinColumn

  PRINT @query
  EXEC(@query)
END TRY
BEGIN CATCH
  PRINT 'COLUMN Not Found!'
    SELECT ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH





-- EXAMPLE 5 (BESTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT):

--##############################################################################################################
-- STEP1: PrintBig (StoredProcedure) to print long text 
--##############################################################################################################
/*
-- You can use print big Stored Procedure to print the long query...... (HERE IT IS)
-- https://www.richardswinbank.net/doku.php?id=tsql:print_big
-- http://stackoverflow.com/questions/4833549/nvarcharmax-still-being-truncated
*/
IF OBJECT_ID('tempdb..#usp_PrintBig') IS NOT NULL
  DROP PROCEDURE #usp_PrintBig
GO
CREATE PROCEDURE #usp_PrintBig (
   @text NVARCHAR(MAX)
 )
AS
--DECLARE @text NVARCHAR(MAX) = 'YourTextHere'
DECLARE @lineSep NVARCHAR(2) = CHAR(13) + CHAR(10)  -- Windows \r\n
 
DECLARE @off INT = 1
DECLARE @maxLen INT = 4000
DECLARE @len INT
 
WHILE @off < LEN(@text)
BEGIN
 
  SELECT @len =
    CASE
      WHEN LEN(@text) - @off - 1 <= @maxLen THEN LEN(@text)
      ELSE @maxLen
             - CHARINDEX(REVERSE(@lineSep),  REVERSE(SUBSTRING(@text, @off, @maxLen)))
             - LEN(@lineSep)
             + 1
    END
  PRINT SUBSTRING(@text, @off, @len)
  --PRINT '@off=' + CAST(@off AS VARCHAR) + ' @len=' + CAST(@len AS VARCHAR)
  SET @off += @len + LEN(@lineSep)
END
GO





--############################################################################################################
-- STEP 2:    GET ALL COLLUMN FROM A JOINED QUERY, SEARCH IN COLUMN NAME AND SORT THEM!!
--############################################################################################################

BEGIN TRY
  DECLARE @columnNameLike NVARCHAR(200) = '%67676%'
  DECLARE @query NVARCHAR(MAX)
  DECLARE @T1 NVARCHAR(200) = 'CustomerInformations'
  DECLARE @T1_JoinColumn NVARCHAR(200) = 'CustomerDynamicInfoId'
  DECLARE @T2 NVARCHAR(200) = 'CustomerDynamicInformations'
  DECLARE @T2_JoinColumn VARCHAR(200) = 'Id'

  SET @query = 'SELECT '+ CHAR(13)
  SELECT @query = @query + TABLE_NAME + '.' + COLUMN_NAME +
  --' AS [' + CASE TABLE_NAME WHEN @T1 THEN COLUMN_NAME+' (T1)' WHEN @T2 THEN COLUMN_NAME+' (T2)' END + ']' +
  ',' + CHAR(13) 
  FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE (TABLE_NAME = @T1 OR TABLE_NAME = @T2) 
  AND COLUMN_NAME LIKE @columnNameLike
  ORDER BY COLUMN_NAME

  SET @query =  LEFT(@query, LEN(@query) - 2) + CHAR(13) 
  + ' FROM ' + @T1 
  + ' INNER JOIN ' + @T2 
  + ' ON '+ @T1 + '.' + @T1_JoinColumn + '=' + @T2 + '.' + @T2_JoinColumn

  EXEC(@query)
  EXEC #usp_PrintBig @query 
  --PRINT @query
  /* 
    -- IF Your table has too many columns, then you might encounter TRUNCATION of query text when printing, 
    -- then use this Temporary StoredProcedure (#usp_PrintBig) to print long text
    -- EXEC #usp_PrintBig @query 
  */
END TRY
BEGIN CATCH
    SELECT 'Column Not Found in either table!' as ErrorMessage
   ,ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorDetail;
END CATCH








------------- AGAIN Modified for DataType & Length (MoreDetailed, BESTTTTT) --------------
BEGIN TRY
 DECLARE @columnNameLike NVARCHAR(200) = '%Name%'
 DECLARE @query NVARCHAR(MAX)
 DECLARE @T1 NVARCHAR(200) = 'CustomerInformations'
 DECLARE @T1_JoinColumn NVARCHAR(200) = 'CustomerDynamicInfoId'
 DECLARE @T2 NVARCHAR(200) = 'CustomerDynamicInformations'
 DECLARE @T2_JoinColumn VARCHAR(200) = 'Id'

 SET @query = 'SELECT '+ CHAR(13)
 SELECT @query = @query + TABLE_NAME + '.' + COLUMN_NAME +
 ' AS ' + QUOTENAME(COLUMN_NAME + '  @'+
   + CAST(DATA_TYPE AS NVARCHAR(55))+
     CASE 
     WHEN CHARACTER_OCTET_LENGTH IS NOT NULL 
      THEN '('+ CAST(ISNULL(CHARACTER_OCTET_LENGTH, '') as NVARCHAR(10))+ ')'
     ELSE ''
     END
 + CASE TABLE_NAME WHEN @T1 THEN ' <T1>' WHEN @T2 THEN ' <T2>' END )
 + ',' + CHAR(13) 
 FROM INFORMATION_SCHEMA.COLUMNS 
 WHERE (TABLE_NAME = @T1 OR TABLE_NAME = @T2) 
 AND COLUMN_NAME LIKE @columnNameLike
 ORDER BY COLUMN_NAME

 SET @query =  LEFT(@query, LEN(@query) - 2) + CHAR(13) 
 + 'FROM ' + @T1 
 + ' INNER JOIN ' + @T2 
 + ' ON '+ @T1 + '.' + @T1_JoinColumn + '=' + @T2 + '.' + @T2_JoinColumn

 EXEC(@query)
 EXEC #usp_PrintBig @query 
 --PRINT @query
 /* 
   -- IF Your table has too many columns, then you might encounter TRUNCATION of query text when printing, 
   -- then use this Temporary StoredProcedure (#usp_PrintBig) to print long text
   -- EXEC #usp_PrintBig @query 
 */
END TRY
BEGIN CATCH
    SELECT 'Column Not Found in either table!' as ErrorMessage
  ,ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorDetail;
END CATCH





-- GET ALL COLUMN NAME OF a Table as String 
DECLARE @str NVARCHAR(MAX);
SELECT @str = Stuff((
  SELECT ',' + QUOTENAME(Column_Name) FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE TABLE_NAME ='tbl_student' 
  AND COLUMN_NAME LIKE '%%'
  For XML Path ('')) ,1 , 1, ''
)

PRINT @str;
EXEC('SELECT '+@str+' FROM tbl_student');




--======================= GET ALL Column, Their DataType, And Allow Null State of a Table =======================
SELECT COLUMN_NAME as ColumnName, CAST(DATA_TYPE AS NVARCHAR(55)) +
  CASE 
  WHEN CHARACTER_OCTET_LENGTH IS NOT NULL 
   THEN ' ('+ cast(ISNULL(CHARACTER_OCTET_LENGTH, '') as NVARCHAR(10))+ ')'
  ELSE '' END
  AS DataTypem,
  CASE 
   WHEN IS_NULLABLE = 'YES' THEN '1'
   ELSE '0'
  END
  AS AllowNulls
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MenuConfigs'







--##############################################################################################################
-- Error Loggin in ErrorLog table, Microsoft recommended way
--##############################################################################################################


-- Create table ErrorLog first
CREATE TABLE [dbo].[ErrorLog] (
        [ErrorLogID]         [int] IDENTITY(1, 1) NOT NULL,
        [ErrorTime]          [datetime] NOT NULL,
        [UserName]           [sysname] NOT NULL,
        [ErrorNumber]        [int] NOT NULL,
        [ErrorSeverity]      [int] NULL,
        [ErrorState]         [int] NULL,
        [ErrorProcedure]     [nvarchar](126) NULL,
        [ErrorLine]          [int] NULL,
        [ErrorMessage]       [nvarchar](4000) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ErrorLog]
    ADD
    CONSTRAINT [PK_ErrorLog_ErrorLogID]
    PRIMARY KEY
    CLUSTERED
    ([ErrorLogID])
    ON [PRIMARY]
GO
ALTER TABLE [dbo].[ErrorLog]
    ADD
    CONSTRAINT [DF_ErrorLog_ErrorTime]
    DEFAULT (getdate()) FOR [ErrorTime]
GO





-- EXAMPLE  of Calling uspLogError  from  inside another Stored Procedure
CREATE PROCEDURE [HumanResources].[uspUpdateEmployeeHireInfo]
    -- paramssssss
    -- paramssssss
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION;
            -- DO SOME WORK HERE
            -- DO SOME WORK HERE
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- Rollback any active or uncommittable transactions before inserting information in the ErrorLog
        IF @@TRANCOUNT > 0  ROLLBACK TRANSACTION;
        EXECUTE [dbo].[uspLogError];
    END CATCH;
END;






/*
-- uspPrintError prints error information about the error that caused 
-- execution to jump to the CATCH block of a TRY...CATCH construct. 
-- Should be executed from within the scope of a CATCH block otherwise 
-- it will return without printing any error information.
*/
CREATE PROCEDURE [dbo].[uspPrintError]
AS
BEGIN
    SET NOCOUNT ON;

    -- Print error information. 
    PRINT 'Error ' + CONVERT(varchar(50), ERROR_NUMBER()) +
          ', Severity ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
          ', State ' + CONVERT(varchar(5), ERROR_STATE()) + 
          ', Procedure ' + ISNULL(ERROR_PROCEDURE(), '-') + 
          ', Line ' + CONVERT(varchar(5), ERROR_LINE());
    PRINT ERROR_MESSAGE();
END;






/*
-- uspLogError logs error information in the ErrorLog table about the 
-- error that caused execution to jump to the CATCH block of a 
-- TRY...CATCH construct. This should be executed from within the scope 
-- of a CATCH block otherwise it will return without inserting error 
-- information. 
*/
CREATE PROCEDURE [dbo].[uspLogError] 
    @ErrorLogID [int] = 0 OUTPUT -- contains the ErrorLogID of the row inserted by uspLogError in the ErrorLog table
AS                               
BEGIN
    SET NOCOUNT ON;
    -- Output parameter value of 0 indicates that error information was not logged
    SET @ErrorLogID = 0;

    BEGIN TRY
        IF ERROR_NUMBER() IS NULL RETURN; -- Return if there is no error information to log

        -- Return if inside an uncommittable transaction.
        -- Data insertion/modification is not allowed when 
        -- a transaction is in an uncommittable state.
        IF XACT_STATE() = -1
        BEGIN
            PRINT 'Cannot log error since the current transaction is in an uncommittable state. ' 
                + 'Rollback the transaction before executing uspLogError in order to successfully log error information.';
            RETURN;
        END

        INSERT [dbo].[ErrorLog] 
        (
            [UserName], 
            [ErrorNumber], 
            [ErrorSeverity], 
            [ErrorState], 
            [ErrorProcedure], 
            [ErrorLine], 
            [ErrorMessage]
        ) 
        VALUES 
        (
            CONVERT(sysname, CURRENT_USER), 
            ERROR_NUMBER(),
            ERROR_SEVERITY(),
            ERROR_STATE(),
            ERROR_PROCEDURE(),
            ERROR_LINE(),
            ERROR_MESSAGE()
        );

        SET @ErrorLogID = @@IDENTITY; -- Pass back the ErrorLogID of the row inserted
    END TRY
    BEGIN CATCH
        PRINT 'An error occurred in stored procedure uspLogError: ';
        EXECUTE [dbo].[uspPrintError];
        RETURN -1;
    END CATCH
END;









--=============================== CHECK IF DATABASE EXISTS ===============================
IF EXISTS (SELECT * FROM   master..sysdatabases WHERE  name = N'FinCrime')
BEGIN
    PRINT 'Database Exists'
    --DROP DATABASE FinCrime
END
ELSE 
BEGIN
    PRINT 'Create Database'
    --CREATE DATABASE FinCrime
END 







--=============================== GET ALL LAST EXECUTED QUERIES (IN SQL Server) ===============================
SELECT execquery.last_execution_time AS [Date Time],execsql.TEXT AS [Script]
FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_execution_time DESC





--======================= Generate Script For DROP Constraints for a Table =============================
-- This script may come in handy in times when you want to drop a table but you cant because of foreign key, 
-- use this script to generate DROP CONSTRAINT Script
-- ALTER TABLE dbo.ProductVendor DROP CONSTRAINT FK_ProductVendor_Product_ProductID
DECLARE @Sql VARCHAR(300);
DECLARE @TableName sysname = 'Product'
DECLARE @SchemaName sysname = 'dbo'
 
  -- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
  DECLARE myCursor CURSOR FOR
     SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + name
       FROM sys.foreign_keys 
      WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = @SchemaName
        AND  OBJECT_NAME(referenced_object_id) = @TableName
 
   OPEN myCursorr
   FETCH NEXT FROM myCursor INTO @Sql
 
   WHILE @@FETCH_STATUS = 0
     BEGIN
       PRINT @Sql;
       --EXEC (@Sql);
       FETCH NEXT FROM myCursor INTO @Sql;
     END
 
  CLOSE myCursor;
  DEALLOCATE myCursor;






--#######################################################################################
-- BACKUP DATABASE SCRIPT FOR Local/ Networked / Remote Server (LAN)
--#######################################################################################
-- EX-1:
-- To run this query, you have to login as 'sa' (or you have to have enough permission to create backup)
-- ex: BACKUP DATABASE AdvancedTSQL TO DISK = 'D:\FinCrime.BAK'
DECLARE @DatabaseName NVARCHAR(MAX) = 'UCB'
DECLARE @BackupPath NVARCHAR(MAX) = '\\192.168.1.254\ds-shared-drive-2\AMLShare\'
DECLARE @Query NVARCHAR(MAX) = 'BACKUP DATABASE '+@DatabaseName+' TO DISK = '''+@BackupPath + @DatabaseName+ '.bak' + ''''
PRINT @Query
EXEC(@query)



-- EX-2 (Stored Procedure):
--EXEC BackupDatabase 'FinCrime', 'D:\'
ALTER PROCEDURE BackupDatabase
    @DatabaseName NVARCHAR(MAX),  
    @BackupLocation NVARCHAR(MAX) = 'D:\'  
AS  
--SET @BackupLocation NVARCHAR(MAX) = '\\192.168.1.254\ds-shared-drive-2\AMLShare\'    
--SET @BackupLocation NVARCHAR(MAX) = 'D:\db_BAK\'    
DECLARE @dateTime   NVARCHAR(MAX) = (SELECT CONVERT(VARCHAR(24),GETDATE(),102) + ' ' +REPLACE(FORMAT(CAST(GETDATE() AS DATETIME),'hh:mm:ss tt'),':','.'))
DECLARE @backupFile NVARCHAR(MAX) = @backupLocation + REPLACE(REPLACE(@DatabaseName, '[',''),']','')+ '_FULL_'+ @dateTime + '.bak'  
DECLARE @backupName NVARCHAR(MAX) = REPLACE(REPLACE(@DatabaseName,'[',''),']','') +' FULL BACKUP FOR '+ @dateTime  
DECLARE @sqlCommand NVARCHAR(MAX) = 'BACKUP DATABASE ' +@DatabaseName+  ' TO DISK = ''' +@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+ ''', NOSKIP, NOFORMAT'  
PRINT @sqlCommand
EXEC(@sqlCommand)  


-- EX-3:
-- BACKUP DATABASE SCRIPT FOR Local/network
-- ex: BACKUP DATABASE AdvancedTSQL TO DISK = 'D:\AdvancedTSQL.BAK'
--DECLARE @BackupPath NVARCHAR(MAX) = '\\192.168.1.254\ds-shared-drive-2\AMLShare\'
--DECLARE @DatabaseName NVARCHAR(MAX) = 'FinCrime'
--DECLARE @FileName NVARCHAR(MAX) = 'FinCrime.bak'
--DECLARE @Query NVARCHAR(MAX) = 'BACKUP DATABASE '+@DatabaseName+' TO DISK = '''+@BackupPath + @FileName+''''
--PRINT @Query
--EXEC(@query)



  
  
  --====================== ID List to Table (from comma separated string ids) =====================
IF OBJECT_ID('UDF_IDListToTable') IS NOT NULL DROP FUNCTION UDF_IDListToTable
GO
--SELECT * FROM UDF_IDListToTable('1,2,3,4,5', ',')
CREATE FUNCTION [dbo].[UDF_IDListToTable]
 (
    @list          [varchar](MAX),
    @Seperator     CHAR(1)
  )
 RETURNS @tbl TABLE (ID INT)
 WITH 

 EXECUTE AS CALLER
 AS
  BEGIN
    DECLARE @position INT
    DECLARE @NewLine CHAR(2) 
    DECLARE @no INT
    SET @NewLine = CHAR(13) + CHAR(10)

    IF CHARINDEX(@Seperator, @list) = 0
    BEGIN
    INSERT INTO @tbl
    VALUES (@list)
END
ELSE
BEGIN
    SET @position = 1
    SET @list = @list + @Seperator
    WHILE CHARINDEX(@Seperator, @list, @position) <> 0
    BEGIN
        SELECT @no = SUBSTRING(@list,@position,CHARINDEX(@Seperator, @list, @position) - @position)
        IF @no <> '' INSERT INTO @tbl VALUES(@no)
        SET @position = CHARINDEX(@Seperator, @list, @position) + 1
    END
END
RETURN
END












--To check number of open connection in SQL server: 
SELECT DB_NAME(dbid) AS DBName, COUNT(dbid) AS NumberOfConnections, loginame AS LoginName  
FROM sys.sysprocesses  
WHERE dbid > 0  
GROUP BY dbid, loginame;



--To check the number of queries running currently on your server:
SELECT sqltext.TEXT, req.session_id, req.STATUS, req.command, req.cpu_time, req.total_elapsed_time  
FROM sys.dm_exec_requests REQ  
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext;


--Find all dependencies of a table in Sql server 
SELECT referencing_schema_name, referencing_entity_name, referencing_id, referencing_class_desc  
FROM sys.dm_sql_referencing_entities('dbo.tbl_student', 'OBJECT');  




--Shows all the sessions that are currently established in Sql server. 
EXEC sp_who2  
--Or  
EXEC sp_who  



--Shows all ACTIVE sessions that are currently established in SQL server. 
EXEC sp_who 'Active'  
--Or  
EXEC sp_who2 'Active'  



select * from SYSDEPENDS   


--Using below mentioned important T-SQL query, we can get the list of the tables used in the stored procedure. 
SELECT   
NAME as 'List Of Tables'  
FROM SYSOBJECTS  
WHERE ID IN (   SELECT SD.DEPID   
                FROM SYSOBJECTS SO,   
                SYSDEPENDS SD  
                WHERE SO.NAME = 'spStudentsBasicInfo'  ----name of stored procedures  
                AND SD.ID = SO.ID  
            ) 




--Here, I put two objects SYSOBJECTS, SYSDEPENDS and put some inner join on the columns of these two objects.
SELECT SD.DEPID   
                FROM SYSOBJECTS SO,   
                SYSDEPENDS SD  
                WHERE SO.NAME = 'spStudentsBasicInfo'  ----name of stored procedures  
                AND SD.ID = SO.ID  








USE master;  
GO  
-- Return the logical file name.  
SELECT name, physical_name AS CurrentLocation, state_desc  
FROM sys.master_files  
WHERE database_id = DB_ID(N'AdvancedTSQL') 






------------- GET ALL TABLE AND THEIR ROW COUNT ------------------------
SELECT T.name AS [TABLE NAME], 
       I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
       INNER JOIN sys.sysindexes AS I 
               ON T.object_id = I.id 
                  AND I.indid < 2 and I.rows>0
ORDER  BY I.rows DESC 





-- CHANGE PASSWORD AND USE EVERYWHERE AFTER USING RESTORE PRIVIOUS ASSWORD
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN TRANSACTION
UPDATE Users SET Passward = '123' 
SELECT * FROM Users
ROLLBACK TRANSACTION
SELECT * FROM Users







--============================= FIND COLUMN NAME LIKE ===============================
-- EX 1: 
DECLARE @ColumnNameLike NVARCHAR(MAX) = 'Name'
DECLARE @TableName NVARCHAR(MAX) = 'CustomerDynamicInformations'
DECLARE @Sql NVARCHAR(MAX) = ''
SELECT @Sql += QUOTENAME(COLUMN_NAME) + ','
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME LIKE '%'+@ColumnNameLike+'%'
ORDER BY COLUMN_NAME
SET @Sql = ('SELECT '+ SUBSTRING(@Sql, 0, LEN(@Sql)) +' FROM '+ @TableName)
--PRINT @Sql 
EXECUTE(@Sql)




-- EX 2:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'CustomerDynamicInformations'
AND COLUMN_NAME LIKE '%prof%'

SELECT IProfession,EProfession
FROM CustomerDynamicInformations





------------- GET ALL KEYS (FOREIGN+PRIMARY) OF A DATABASE
IF OBJECT_ID('tempdb..#TempAssociation') IS NOT NULL DROP TABLE #TempAssociation
SELECT f.name AS ForeignKey, 
SCHEMA_NAME(f.SCHEMA_ID) SchemaName, 
OBJECT_NAME(f.parent_object_id) AS TableName, 
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName, 
SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName, 
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName, 
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName
INTO #TempAssociation
FROM sys.foreign_keys AS f 
INNER JOIN sys.foreign_key_columns AS fc 
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id 
ON f.OBJECT_ID = fc.constraint_object_id 
SELECT * FROM #TempAssociation WHERE ColumnName like '%ParentId%' or ColumnName like '%Id%'
DROP TABLE  #TempAssociation







--#######################################################################################
-- (BESTTTT) V1 ::: Get Dynamic Columns And Data Using UNPIVOT 
--#######################################################################################

-- EXEC spGetDynamicColumnsAndDataUsingUnpivot 'CustomerInformations'
-- EXEC spGetDynamicColumnsAndDataUsingUnpivot 'CustomerInformations', 5
-- EXEC spGetDynamicColumnsAndDataUsingUnpivot 'CustomerInformations', 5, 'Id'
-- EXEC spGetDynamicColumnsAndDataUsingUnpivot @tblName='CustomerInformations', @KeyColumnName='Id', @ValueToMatchWithKeyColumn=5
IF(OBJECT_ID('spGetDynamicColumnsAndDataUsingUnpivot') IS NOT NULL) DROP PROCEDURE spGetDynamicColumnsAndDataUsingUnpivot
GO
CREATE PROCEDURE dbo.spGetDynamicColumnsAndDataUsingUnpivot
(
	@tblName VARCHAR(MAX),
	@ValueToMatchWithKeyColumn VARCHAR(MAX) = '',
	@KeyColumnName VARCHAR(MAX) = 'Id'
)
AS
    IF OBJECT_ID('tempdb..##Temp') IS NOT NULL DROP TABLE ##Temp;
	DECLARE @ColumnNames NVARCHAR(MAX) = '', @Values NVARCHAR(MAX) = '', @SQL NVARCHAR(MAX) = '';

	SELECT @ColumnNames += ',' + QUOTENAME(COLUMN_NAME), @Values += ',' + QUOTENAME(COLUMN_NAME) + ' = CONVERT(VARCHAR(100), ' + QUOTENAME(COLUMN_NAME) + ')'
	FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_NAME = @tblName AND COLUMN_NAME <> @KeyColumnName;
	
	SET @SQL = N'Select * into ##Temp
	FROM
	(
		SELECT ' + @KeyColumnName + @Values + '
		FROM ' + @tblName 
		+IIF(@ValueToMatchWithKeyColumn <> '', ' WHERE '+ @KeyColumnName + '='''+ @ValueToMatchWithKeyColumn +'''', '')
		+ '
	) AS DerivedTable
	UNPIVOT
	(
		Value FOR ColumnName IN (' + STUFF(@ColumnNames, 1, 1, '') + ')
	) AS UnPvt;'


	EXEC sp_executesql @SQL;
	SELECT * FROM ##Temp;

	
	



----------------------------------------------------------------
-- (BETTER) V2::: Get Dynamic Columns And Data Using UNPIVOT
----------------------------------------------------------------

-- EXEC spGetDynamicColumnsAndDataUsingUnpivot
IF(OBJECT_ID('spGetDynamicColumnsAndDataUsingUnpivot') IS NOT NULL) DROP PROCEDURE spGetDynamicColumnsAndDataUsingUnpivot
GO
CREATE PROCEDURE dbo.spGetDynamicColumnsAndDataUsingUnpivot
AS
    IF OBJECT_ID('tempdb..##Temp') IS NOT NULL DROP TABLE ##Temp;
	DECLARE @ObjectName VARCHAR(100) = 'CustomerInformations', @KeyColumn VARCHAR(100) = 'Id';
	DECLARE @ColumnNames NVARCHAR(MAX) = '', @Values NVARCHAR(MAX) = '', @SQL NVARCHAR(MAX) = '';

	SELECT @ColumnNames += ',' + QUOTENAME(COLUMN_NAME), @Values += ',' + QUOTENAME(COLUMN_NAME) + ' = CONVERT(VARCHAR(100), ' + QUOTENAME(COLUMN_NAME) + ')'
	FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_NAME = @ObjectName AND COLUMN_NAME <> @KeyColumn;


	SET @SQL = N'Select * into ##Temp
	FROM
	(
		SELECT ' + @KeyColumn + @Values + '
		FROM ' + @ObjectName + '
	) AS DRV
	UNPIVOT
	(
		Value FOR ColumnName IN (' + STUFF(@ColumnNames, 1, 1, '') + ')
	) AS UnPVT;';


	--PRINT @SQL
	EXEC sp_executesql @SQL;
	SELECT * FROM ##Temp;

	
	
	
	
----------------------------------------------------------------
-- (QUERY) V3::: Get Dynamic Columns And Data Using UNPIVOT
----------------------------------------------------------------

IF OBJECT_ID('tempdb..##Temp') IS NOT NULL DROP TABLE ##Temp;
DECLARE @ObjectName VARCHAR(100) = 'CustomerInformations', @KeyColumn VARCHAR(100) = 'Id';
DECLARE @ColumnNames NVARCHAR(MAX) = '', @Values NVARCHAR(MAX) = '', @SQL NVARCHAR(MAX) = '';

SELECT @ColumnNames += ',' + QUOTENAME(COLUMN_NAME), @Values += ',' + QUOTENAME(COLUMN_NAME) + ' = CONVERT(VARCHAR(100), ' + QUOTENAME(COLUMN_NAME) + ')'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @ObjectName AND COLUMN_NAME <> @KeyColumn;


SET @SQL = N'Select * into ##Temp
FROM
(
	SELECT ' + @KeyColumn + @Values + '
	FROM ' + @ObjectName + ' WHERE '+ @KeyColumn + '='+ '3'
	+ '
) AS DRV
UNPIVOT
(
	Value FOR ColumnName IN (' + STUFF(@ColumnNames, 1, 1, '') + ')
) AS UnPVT;';

--PRINT @SQL
EXEC sp_executesql @SQL;
SELECT * FROM ##Temp;



以上是关于sql 高级T-SQL脚本(从这里和他们收集)的主要内容,如果未能解决你的问题,请参考以下文章

T-SQL 相当于 Oracle 的收集方法(第一个、最后一个、下一个)?

如何从 T-SQL 存储过程返回表

T-SQL 高级查询

高级T-SQL进阶系列 上篇:使用 APPLY操作符

启用夏令时时如何在 T-SQL 中获取一天的开始和结束?

高级T-SQL第1级的阶梯:使用交叉连接来引入高级T-SQL