Saturday, February 7, 2015

DMV to Find the Ports that SQL Server is Listening On



Query

SELECT      e.name,
            e.endpoint_id,
            e.principal_id,
            e.protocol,
            e.protocol_desc,
            ec.local_net_address,
            ec.local_tcp_port,
            e.[type],
            e.type_desc,
            e.[state],
            e.state_desc,
            e.is_admin_endpoint
FROM        sys.endpoints e
            LEFT OUTER JOIN sys.dm_exec_connections ec
                ON ec.endpoint_id = e.endpoint_id
GROUP BY    e.name,
            e.endpoint_id,
            e.principal_id,
            e.protocol,
            e.protocol_desc,
            ec.local_net_address,
            ec.local_tcp_port,
            e.[type],
            e.type_desc,
            e.[state],
            e.state_desc,
            e.is_admin_endpoint 

Friday, January 30, 2015

Root Blocker Query in SQL Server



Root Blocker Query in SQL Server

SET NOCOUNT ON
SET CONCAT_NULL_YIELDS_NULL OFF
GO
SELECT SPID, BLOCKED, REPLACE (REPLACE (T.TEXT, CHAR(10), ' '), CHAR (13), ' ' ) AS BATCH
INTO #T
FROM SYS.SYSPROCESSES R CROSS APPLY SYS.DM_EXEC_SQL_TEXT(R.SQL_HANDLE) T
GO
WITH BLOCKERS (SPID, BLOCKED, LEVEL, BATCH)
AS
(
SELECT SPID,
BLOCKED,
CAST (REPLICATE ('0', 4-LEN (CAST (SPID AS VARCHAR))) + CAST (SPID AS VARCHAR) AS VARCHAR (1000)) AS LEVEL,
BATCH FROM #T R
WHERE (BLOCKED = 0 OR BLOCKED = SPID)
AND EXISTS (SELECT * FROM #T R2 WHERE R2.BLOCKED = R.SPID AND R2.BLOCKED <> R2.SPID)
UNION ALL
SELECT R.SPID,
R.BLOCKED,
CAST (BLOCKERS.LEVEL + RIGHT (CAST ((1000 + R.SPID) AS VARCHAR (100)), 4) AS VARCHAR (1000)) AS LEVEL,
R.BATCH FROM #T AS R
INNER JOIN BLOCKERS ON R.BLOCKED = BLOCKERS.SPID WHERE R.BLOCKED > 0 AND R.BLOCKED <> R.SPID
)
SELECT N' ' + REPLICATE (N'| ', LEN (LEVEL)/4 - 2) + CASE WHEN (LEN (LEVEL)/4 - 1) = 0 THEN 'HEAD - ' ELSE '|------ ' END + CAST (SPID AS NVARCHAR (10)) + ' ' + BATCH AS BLOCKING_TREE FROM BLOCKERS ORDER BY LEVEL ASC
GO
DROP TABLE #T

GO

Thursday, January 29, 2015

Adding Artical in transaction replication with schema Name change at subscriber (Not required re-initializing of snapshot)



How to add Articles in transaction replication with out reinitializing snapshot

Step-1

Please run the below command and make sure values must be '0' for the database which is participating in Replication

select immediate_sync , allow_anonymous from syspublications



If You find the values are '1' please change the values from the below commands

EXEC sp_changepublication @publication = 'Publisher name', @property =
N'allow_anonymous', @value='true'
Go
EXEC sp_changepublication @publication = 'Publisher name', @property =
N'immediate_sync', @value='true'
Go

Step-2

Adding articles to Publisher , run the below script.

exec sp_addarticle @publication = N'Publisher name',
@article = N'Publisher Articles',
@source_owner = N'dbo',
@source_object = N'Source Publisher Table',
@type = N'logbased',
@description = N'',
@creation_script = N'',
@pre_creation_cmd = N'delete',
@schema_option = 0x000000000803509F,
@identityrangemanagementoption = N'none',
@destination_table = N'Destination Table',
@destination_owner = N'Schema Name',
@status = 24,
@vertical_partition = N'false',
@ins_cmd = N'CALL [dbo].[sp_MSins_12Name_insert_sp]',
@del_cmd = N'CALL [dbo].[sp_MSdel_12Name_delete_sp]',
@upd_cmd = N'SCALL [dbo].[sp_MSupd_12Name_Update_sp]',
@force_invalidate_snapshot=1

Note;

@destination_owner = N'Schema Name', --->change the schema name here for subscriber table.

There were three sp will use in replication for moving data from PUB to SUB so please adde some name to the below red coloured space for recognising sp's

   @ins_cmd = N'CALL [dbo].[sp_MSins_12Name_insert_sp]',
   @del_cmd = N'CALL [dbo].[sp_MSdel_12Name_delete_sp]',
   @upd_cmd = N'SCALL [dbo].[sp_MSupd_12Name_Update_sp]'

Step-3

Add the subscription to publisher which we have added before.

EXEC sp_addsubscription @publication = 'Publication Name',
           @subscription_type = N'push',
           @article = 'Articles name',
           @subscriber ='Subscriber server name', @destination_db = 'Subscriber Database Name',
           @reserved='Internal'


Step-4

select * from msdb..sysjobs where name like '%Publisher name%'


Run the job of snapshot which contain step-1 '‘Snapshot Agent startup message

Make sure that you have see only added articles only snapshot will run.see the below screen shot.



From the above we have added 4 articles at a time.

when you launch the replication monitor,

First .sre and .sch ,.bcp scripts on subscriber end  then bulk inserts will inserts data from PUB to SUB find the screen shot.



Sql Server Information Part-1


Need to know all the information about Sql server


SELECT SERVERPROPERTY('MachineName') AS [MachineName], SERVERPROPERTY('ServerName') AS [ServerName],
SERVERPROPERTY('InstanceName') AS [Instance], SERVERPROPERTY('IsClustered') AS [IsClustered],
SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS],
SERVERPROPERTY('Edition') AS [Edition], SERVERPROPERTY('ProductLevel') AS [ProductLevel],
SERVERPROPERTY('ProductVersion') AS [ProductVersion], SERVERPROPERTY('ProcessID') AS [ProcessID],
SERVERPROPERTY('Collation') AS [Collation], SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled],

SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly];


CPU  and RAM Information

SELECT cpu_count AS [Logical CPU Count], hyperthread_ratio AS [Hyperthread Ratio],
cpu_count/hyperthread_ratio AS [Physical CPU Count],
physical_memory_in_bytes/1048576 AS [Physical Memory (MB)]

FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);

Configuration Values of Sql Server

SELECT name, value, value_in_use, [description]
FROM sys.configurations WITH (NOLOCK)

ORDER BY name  OPTION (RECOMPILE);

Calculates average stalls per read, per write, and per total input/output for each database file

SELECT DB_NAME(fs.database_id) AS [Database Name], mf.physical_name, io_stall_read_ms, num_of_reads,
CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1)) AS [avg_read_stall_ms],io_stall_write_ms,
num_of_writes,CAST(io_stall_write_ms/(1.0+num_of_writes) AS NUMERIC(10,1)) AS [avg_write_stall_ms],
io_stall_read_ms + io_stall_write_ms AS [io_stalls], num_of_reads + num_of_writes AS [total_io],
CAST((io_stall_read_ms + io_stall_write_ms)/(1.0 + num_of_reads + num_of_writes) AS NUMERIC(10,1))
AS [avg_io_stall_ms]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf WITH (NOLOCK)
ON fs.database_id = mf.database_id
AND fs.[file_id] = mf.[file_id]

ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);

-- Helps you determine which database files on the entire instance have the most I/O bottlenecks
-- This can help you decide whether certain LUNs are overloaded and whether you might
-- want to move some files to a different location

Get CPU utilization by database

WITH DB_CPU_Stats
AS
(SELECT DatabaseID, DB_Name(DatabaseID) AS [DatabaseName], SUM(total_worker_time) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
 CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID]
              FROM sys.dm_exec_plan_attributes(qs.plan_handle)
              WHERE attribute = N'dbid') AS F_DB
 GROUP BY DatabaseID)
SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
       DatabaseName, [CPU_Time_Ms],
       CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
FROM DB_CPU_Stats
WHERE DatabaseID > 4 -- system databases
AND DatabaseID <> 32767 -- ResourceDB

ORDER BY row_num OPTION (RECOMPILE);

Get total buffer usage by database for current instance

SELECT DB_NAME(database_id) AS [Database Name],
COUNT(*) * 8/1024.0 AS [Cached Size (MB)]
FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
WHERE database_id > 4 -- system databases
AND database_id <> 32767 -- ResourceDB
GROUP BY DB_NAME(database_id)
ORDER BY [Cached Size (MB)] DESC OPTION (RECOMPILE);

-- Tells you how much memory (in the buffer pool)
-- is being used by each database on the instance
-- Clear Wait Stats

-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

Top waits for server instance since last restart

WITH Waits AS
(SELECT wait_type, wait_time_ms / 1000. AS wait_time_s,
100. * wait_time_ms / SUM(wait_time_ms) OVER() AS pct,
ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS rn
FROM sys.dm_os_wait_stats WITH (NOLOCK)
WHERE wait_type NOT IN (N'CLR_SEMAPHORE',N'LAZYWRITER_SLEEP',N'RESOURCE_QUEUE',N'SLEEP_TASK',
N'SLEEP_SYSTEMTASK',N'SQLTRACE_BUFFER_FLUSH',N'WAITFOR', N'LOGMGR_QUEUE',N'CHECKPOINT_QUEUE',
N'REQUEST_FOR_DEADLOCK_SEARCH',N'XE_TIMER_EVENT',N'BROKER_TO_FLUSH',N'BROKER_TASK_STOP',N'CLR_MANUAL_EVENT',
N'CLR_AUTO_EVENT',N'DISPATCHER_QUEUE_SEMAPHORE', N'FT_IFTS_SCHEDULER_IDLE_WAIT',
N'XE_DISPATCHER_WAIT', N'XE_DISPATCHER_JOIN', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
N'ONDEMAND_TASK_QUEUE', N'BROKER_EVENTHANDLER', N'SLEEP_BPOOL_FLUSH'))
SELECT W1.wait_type,
CAST(W1.wait_time_s AS DECIMAL(12, 2)) AS wait_time_s,
CAST(W1.pct AS DECIMAL(12, 2)) AS pct,
CAST(SUM(W2.pct) AS DECIMAL(12, 2)) AS running_pct
FROM Waits AS W1
INNER JOIN Waits AS W2
ON W2.rn <= W1.rn
GROUP BY W1.rn, W1.wait_type, W1.wait_time_s, W1.pct
HAVING SUM(W2.pct) - W1.pct < 99 OPTION (RECOMPILE); -- percentage threshold

-- Common Significant Wait types with BOL explanations

-- *** Network Related Waits ***
-- ASYNC_NETWORK_IO        Occurs on network writes when the task is blocked behind the network

-- *** Locking Waits ***
-- LCK_M_IX                Occurs when a task is waiting to acquire an Intent Exclusive (IX) lock
-- LCK_M_IU                Occurs when a task is waiting to acquire an Intent Update (IU) lock
-- LCK_M_S                Occurs when a task is waiting to acquire a Shared lock

-- *** I/O Related Waits ***
-- ASYNC_IO_COMPLETION  Occurs when a task is waiting for I/Os to finish
-- IO_COMPLETION        Occurs while waiting for I/O operations to complete.
--                      This wait type generally represents non-data page I/Os. Data page I/O completion waits appear
--                      as PAGEIOLATCH_* waits
-- PAGEIOLATCH_SH        Occurs when a task is waiting on a latch for a buffer that is in an I/O request.
--                      The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
-- PAGEIOLATCH_EX        Occurs when a task is waiting on a latch for a buffer that is in an I/O request.
--                      The latch request is in Exclusive mode. Long waits may indicate problems with the disk subsystem.
-- WRITELOG             Occurs while waiting for a log flush to complete.
--                      Common operations that cause log flushes are checkpoints and transaction commits.
-- PAGELATCH_EX            Occurs when a task is waiting on a latch for a buffer that is not in an I/O request.
--                      The latch request is in Exclusive mode.
-- BACKUPIO                Occurs when a backup task is waiting for data, or is waiting for a buffer in which to store data

-- *** CPU Related Waits ***
-- SOS_SCHEDULER_YIELD  Occurs when a task voluntarily yields the scheduler for other tasks to execute.
--                      During this wait the task is waiting for its quantum to be renewed.

-- THREADPOOL            Occurs when a task is waiting for a worker to run on.
--                      This can indicate that the maximum worker setting is too low, or that batch executions are taking
--                      unusually long, thus reducing the number of workers available to satisfy other batches.
-- CX_PACKET            Occurs when trying to synchronize the query processor exchange iterator

--                        You may consider lowering the degree of parallelism if contention on this wait type becomes a problem

Signal Waits for instance

SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [%signal (cpu) waits],
       CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [%resource waits]
FROM sys.dm_os_wait_stats OPTION (RECOMPILE);



-- Signal Waits above 10-15% is usually a sign of CPU pressure

Get logins that are connected and how many sessions they have

SELECT login_name, COUNT(session_id) AS [session_count]
FROM sys.dm_exec_sessions WITH (NOLOCK)
GROUP BY login_name
ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);

-- This can help characterize your workload and

-- determine whether you are seeing a normal level of activity

Page Life Expectancy (PLE) value for each NUMA node in current instance 

SELECT @@SERVERNAME AS [Server Name], [object_name], instance_name, cntr_value AS [Page Life Expectancy]
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);

-- PLE is a good measurement of memory pressure.
-- Higher PLE is better. Watch the trend, not the absolute value.

-- This will only return one row for non-NUMA systems.

Memory Grants Pending value for current instance

SELECT @@SERVERNAME AS [Server Name], [object_name], cntr_value AS [Memory Grants Pending]                                                                                                      
FROM sys.dm_os_performance_counters WITH (NOLOCK)
WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);


-- Memory Grants Pending above zero for a sustained period is a very strong indicator of memory pressure



SQL Server Uptime



Some time we need to find out the Sql Server time 

SET NOCOUNT ON
DECLARE @crdate DATETIME, @hr VARCHAR(50), @min VARCHAR(5)
SELECT @crdate=crdate FROM sysdatabases WHERE NAME='tempdb'
SELECT @hr=(DATEDIFF ( mi, @crdate,GETDATE()))/60
IF ((DATEDIFF ( mi, @crdate,GETDATE()))/60)=0
SELECT @min=(DATEDIFF ( mi, @crdate,GETDATE()))
ELSE
SELECT @min=(DATEDIFF ( mi, @crdate,GETDATE()))-((DATEDIFF( mi, @crdate,GETDATE()))/60)*60
PRINT 'SQL Server "' + CONVERT(VARCHAR(20),SERVERPROPERTY('SERVERNAME'))+'" is Online for the past '+@hr+' hours & '+@min+' minutes'
IF NOT EXISTS (SELECT 1 FROM master.dbo.sysprocesses WHERE program_name = N'SQLAgent - Generic Refresher')
BEGIN
PRINT 'SQL Server is running but SQL Server Agent <<NOT>> running'
END
ELSE BEGIN
PRINT 'SQL Server and SQL Server Agent both are running'

END

How to Find The % of Job completed

How to Find The % of Job completed 



SELECT A.NAME,B.TOTAL_ELAPSED_TIME/60000 AS [Running Time],
B.ESTIMATED_COMPLETION_TIME/60000 AS [Remaining],
B.PERCENT_COMPLETE as [%],(SELECT TEXT FROM sys.dm_exec_sql_text(B.SQL_HANDLE))AS COMMAND FROM
msdb.dbo.sysjobs A, sys.dm_exec_requests B
WHERE  Job_id LIKE '052280DF-7799-46AB-A259-A522BB90FB01'
order by percent_complete desc,B.TOTAL_ELAPSED_TIME/60000 desc

Note:please replace the Job_id

How To Find Service Accounts of SQL server through t-SQL



How To Find Service Accounts of SQL server through t-SQL

DECLARE       @DBEngineLogin       VARCHAR(100)
DECLARE       @AgentLogin          VARCHAR(100)
EXECUTE       master.dbo.xp_instance_regread

              @rootkey      = N'HKEY_LOCAL_MACHINE',

              @key          = N'SYSTEM\CurrentControlSet\Services\MSSQLServer',

              @value_name   = N'ObjectName',

              @value        = @DBEngineLogin OUTPUT

 EXECUTE       master.dbo.xp_instance_regread

              @rootkey      = N'HKEY_LOCAL_MACHINE',

              @key          = N'SYSTEM\CurrentControlSet\Services\SQLServerAgent',

              @value_name   = N'ObjectName',

              @value        = @AgentLogin OUTPUT

 SELECT        [DBEngineLogin] = @DBEngineLogin, [AgentLogin] = @AgentLogin

GO
SELECT servicename, service_account
FROM   sys.dm_server_services


GO

Tuesday, January 20, 2015

ERROR:The sql server database services feature failed when it was initially intalled.the feature must be removed before the current scenarion can proceed



Today when I am Adding node to sql server 2012 cluster I got one of the

Error :

The sql server database services feature failed when it was initially installed.the feature must be removed before the current scenario can proceed

For the above error says:there was problem on the installation which we have done already on first node so when we are trying to add node to specific cluster it through this kind of errors.

Resolution:

when the installation of sql server is success we can see the values on the registry  will be always '1'on the location:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.\ConfigurationState

when the installation having some problem the value in registry will be '2' you can see in the screen shot below.


So this is why our add node installation is getting failed.

when we are installing on the first node all the installation went cool but at the end our DQS was failed.you can see the error from the below screenshot




To resolve the issue with DQS ,we have manually ran the DQSIntaller.exe on the cluster now the DQS is running fine but it not updated in the registry.

That is why I got this error why I am running add not the cluster it is getting failed so to bi-pass this error I have made a change in the registry file

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.\ConfigurationState

SQL_DQ_FULL DWORD 0x00001(1)

Finally I have added node to cluster successfully.

(OR) you can run the repair from media setup file you can fix the problem like this and then you can add node to cluster as well.

Note:Before change any registry setting take the backup of the registry



Monday, January 19, 2015

FRAGMENTATION INFORMATION FOR A DATABASE WITH PAGE COUNTS AND AVG_FRAG



Script

SELECT object_name(object_id) as objectname, index_id, avg_fragmentation_in_percent, page_count
FROM sys.dm_db_index_physical_stats(DB_ID('Databasename'),
null, NULL, NULL, NULL)
where avg_fragmentation_in_percent >30 and page_count >1000

Note:please replace the database

Generally the page count > 1000 and avg_fragmentation_in_percent>30 indicates there was a performance degrade

SQL WAIT TYPES EXPLANATION

ASYNC_NETWORK_IO:

This wait type is RBAR (Row-By-Agonizing-Row) processing of results in a client, instead of caching the results client-side and telling SQL Server to send more. A common misconception is that this wait type is usually caused by network problems

CXPACKET:

This wait type always accrues when parallelism happens, as the control thread in a parallel operation waits until all threads have completed. However, when parallel threads are given unbalanced amounts of work to do, the threads that finish early also accrue this wait type, leading to it maybe becoming the most prevalent. So this one could be benign, as the workload has lots of good parallelism, but could be malignant if there’s unwanted parallelism or problems causing skewed distribution of work among parallel threads.

LCK_M_IX:

This wait type occurs when a thread is waiting for a table or page IX lock so that a row insert or update can occur. It could be from lock escalation to a table X or S lock causing all other threads to wait to be able to insert/update.

LCK_M_X:

 This wait type commonly occurs when lock escalation is happening. It could also be caused by using a restrictive isolation level like REPEATABLE_READ or SERIALIZABLE that requires S and IS locks to be held until the end of a transaction. Note that distributed transactions change the isolation level to SERIALIZABLE under the covers – something that’s bitten several of our clients before we helped them. Someone could also have inhibited row locks on a clustered index causing all inserts to acquire page X locks – this is very uncommon though.

PAGEIOLATCH_SH:

 This wait type occurs when a thread is waiting for a data file page to be read into memory. Common causes of this wait being the most prevalent are when the workload doesn't fit in memory and the buffer pool has to keep evicting pages and reading others in from disk, or when query plans are using table scans instead of index seeks, or when the buffer pool is under memory pressure which reduces the amount of space available for data.

 PAGELATCH_EX:

The two classic causes of this wait type are tempdb allocation bitmap contention (from lots of concurrent threads creating and dropping temp tables combined with a small number of tempdb files and not having TF1118 enabled) and an insert hotspot (from lots of concurrent threads inserting small rows into a clustered index with an identity value, leading to contention on the index leaf-level pages). There are plenty of other causes of this wait type too, but none that would commonly lead to it being the leading wait type over the course of a week.

 SOS_SCHEDULER_YIELD:

The most common cause of this wait type is that the workload is memory resident and there is no contention for resources, so threads are able to repeatedly exhaust their scheduling quanta (4ms), registering SOS_SCHEDULER_YIELD when they voluntarily yield the processor. An example would be scanning through a large number of pages in an index. This may or may not be a good thing.

WRITELOG:

This wait type is common to see in the first few top waits on servers as the transaction log is often one of the chief bottlenecks on a busy server. This could be caused by the I/O subsystem not being able to keep up with the rate of log flushing combined with lots of tiny transactions forcing frequent flushes of minimal-sized log blocks.

Script to get all Primary and foreign Keys in a Database

list of primary keys info on database


select '
ALTER TABLE ['+t.table_name+'] ADD  CONSTRAINT ['+t.constraint_name+'] PRIMARY KEY CLUSTERED 
(
 ['+ u. COLUMN_NAME +'] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON,
 ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO' from INFORMATION_SCHEMA.TABLE_CONSTRAINTS t
, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE u
where CONSTRAINT_TYPE = 'PRIMARY KEY' AND t.CONSTRAINT_NAME = u.CONSTRAINT_NAME
ORDER BY u.TABLE_NAME

list of foreign keys info on database

select '
ALTER TABLE ['+object_name(f.parent_object_id)+'] WITH NOCheck ADD  CONSTRAINT ['+f.name+'] FOREIGN KEY  
 ('+ COL_NAME(fc.parent_object_id,fc.parent_column_id) +') references ['+OBJECT_NAME (f.referenced_object_id)+'] 
 ('+COL_NAME(fc.referenced_object_id,fc.referenced_column_id)+') 
GO'
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id 

  Redshift User          Administration 1.1         Add New Users   Amazon Redshift user accounts can only be created and dropped by a d...