Tool for Scripting Table Data - sql-server

Are there any free tools for scripting MSSQL table data? I'll gladly write one, but am hoping it's been done, and the app matured a bit before/

Here are some scripts I wrote for reverse engineering SQL server schemas. They may be of some use. Also, as a general interest they give some examples of how to get various bits of information out of the data dictionary. I've added an MIT license below to make permission-to-use explicit and for some basic no-implicit-warranty CYA. Enjoy.
-- ====================================================================
-- === reverse_engineer_2005.sql ======================================
-- ====================================================================
--
-- Script to generate table, index, pk, view and fk definitions from
-- a SQL Server 2005 database. Adapted from one I originally wrote
-- for SQL Server 2000. It's not comprehensive (doesn't extract
-- partition schemes) but it does do defaults and computed columns
--
-- Run the script with 'results to text' and cut/paste the output into
-- the editor window. Set the schema as described below.
--
-- Copyright (c) 2004-2008 Concerned of Tunbridge Wells
--
-- Permission is hereby granted, free of charge, to any person
-- obtaining a copy of this software and associated documentation
-- files (the "Software"), to deal in the Software without
-- restriction, including without limitation the rights to use,
-- copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following
-- conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-- OTHER DEALINGS IN THE SOFTWARE.
--
-- ====================================================================
--
set nocount on
-- This does a specific schema. Set the schema here
--
declare #schema varchar (max)
select #schema = 'dbo'
if object_id ('tempdb..#objects') is not null begin
drop table #objects
end
if object_id ('tempdb..#views') is not null begin
drop table #views
end
if object_id ('tempdb..#types') is not null begin
drop table #types
end
-- Gets lists of tables and views belonging to the schema
--
select o.name
,o.object_id
into #objects
from sys.objects o
join sys.schemas s
on s.schema_id = o.schema_id
where o.type in ('U')
and s.name = #schema
select o.name
,o.object_id
into #views
from sys.objects o
join sys.schemas s
on s.schema_id = o.schema_id
where o.type in ('V')
and s.name = #schema
-- Some metadata for rendering types
--
select a.*
into #types
from ((select 'decimal' as typename, 6 as format) union all
(select 'numeric', 6) union all
(select 'varbinary', 1) union all
(select 'varchar', 1) union all
(select 'char', 1) union all
(select 'nvarchar', 1) union all
(select 'nchar', 1)) a
-- This generates 'drop table' and 'drop view' statements
--
select 'if exists (select 1' + char(10) +
' from sys.objects o' + char(10) +
' join sys.schemas s' + char(10) +
' on o.schema_id = s.schema_id' + char(10) +
' where o.name = ''' + o.name + '''' + char(10) +
' and s.name = ''' + #schema +'''' + char(10) +
' and o.type = ''U'') begin' + char(10) +
' drop table [' + #schema + '].[' + o.name + ']' + char(10) +
'end' + char(10) +
'go' + char(10)
from sys.objects o
join #objects o2
on o.object_id = o2.object_id
where o.type = 'U'
select 'if exists (select 1' + char(10) +
' from sys.objects o' + char(10) +
' join sys.schemas s' + char(10) +
' on o.schema_id = s.schema_id' + char(10) +
' where o.name = ''' + o.name + '''' + char(10) +
' and s.name = ''' + #schema + '''' + char(10) +
' and o.type = ''V'') begin' + char(10) +
' drop view [' + #schema + '].[' + o.name + ']' + char(10) +
'end' + char(10) +
'go' + char(10)
from sys.objects o
join #objects o2
on o.object_id = o2.object_id
where o.type = 'V'
-- This generates table definitions
--
select case when c.column_id =
(select min(c2.column_id)
from sys.columns c2
where c2.object_id = o.object_id)
then 'create table [' + #schema + '].[' + isnull(o.name, 'XYZZY') + '] (' + char(10)
else ''
end +
left(' [' +rtrim(c.name) + '] ' +
' ', 48) +
isnull(calc.text,
t.name +
case when tc.format & 2 = 2
then ' (' +convert (varchar, c.precision) +
case when tc.format & 2 = 2
then ', ' + convert (varchar, c.scale)
else ''
end + ')'
when tc.format & 1 = 1
then ' (' + convert (varchar, c.max_length) + ')'
else ''
end + ' ' +
case when c.is_nullable <> 0 then 'null'
else 'not null'
end + isnull(ident.text, isnull(con.text, ''))) +
case when c.column_id =
(select max(c2.column_id)
from sys.columns c2
where c2.object_id = o.object_id)
then char(10) + ')' + char(10) + 'go' + char(10)
else ','
end
from sys.objects o
join #objects o2
on o.object_id = o2.object_id
join sys.columns c
on c.object_id = o.object_id
join sys.types t
on c.user_type_id = t.user_type_id
left join
(select object_id,
column_id,
'as ' + definition as text
from sys.computed_columns) calc
on calc.object_id = o.object_id
and calc.column_id = c.column_id
left join
(select parent_object_id,
parent_column_id,
' default ' + definition as text
from sys.default_constraints) con
on con.parent_object_id = o.object_id
and con.parent_column_id = c.column_id
left join
(select o.object_id,
col.column_id,
' identity (' + convert(varchar, ident_seed(o.name)) + ', ' +
convert(varchar, ident_incr(o.name)) + ')' as text
from sys.objects o
join sys.columns col
on o.object_id = col.object_id
where columnproperty (o.object_id, col.name, 'IsIdentity') = 1) as ident
on ident.object_id = o.object_id
and ident.column_id = c.column_id
left join #types tc
on tc.typename = t.name
where o.type = 'U'
order by o.name,
c.column_id
-- This generates view definitions
--
select definition + char(10) + 'go' + char(10)
from sys.sql_modules c
join sys.objects o
on c.object_id = o.object_id
join #views o2
on o.object_id = o2.object_id
-- This generates PK and unique constraints
--
select case when ik.key_ordinal =
(select min(ik2.key_ordinal)
from sys.index_columns ik2
where ik2.object_id = ik.object_id
and ik2.index_id = ik.index_id)
then 'alter table [' + rtrim (s.name) + '].[' + rtrim(t.name) + ']' + char(10) +
' add constraint [' + rtrim (pk.name) + '] ' +
case when pk.type = 'PK' then 'primary key'
when pk.type = 'UQ' then 'unique'
else 'foobar'
end + char(10) +
' ('
else ' ,'
end +
'[' + rtrim(c.name) + ']' +
case when ik.key_ordinal =
(select max(ik2.key_ordinal)
from sys.index_columns ik2
where ik2.object_id = ik.object_id
and ik2.index_id = ik.index_id)
then ')' + char(10) + 'go' + char(10)
else ''
end
from sys.objects t -- table
join #objects o
on t.object_id = o.object_id
join sys.schemas s
on s.schema_id = t.schema_id
join sys.objects pk -- key
on pk.parent_object_id = t.object_id
join sys.columns c -- columns
on c.object_id = t.object_id
join sys.indexes i -- get index for constraint
on i.object_id = t.object_id
and i.name = pk.name
join sys.index_columns ik -- index column and name
on ik.object_id = i.object_id
and ik.index_id = i.index_id
and ik.column_id = c.column_id -- vvv Get the right index
where c.name = index_col('[' + s.name + '].[' + t.name + ']', i.index_id, ik.key_ordinal)
and pk.type in ('PK', 'UQ') --probably redundant
order by t.object_id,
pk.object_id,
ik.key_ordinal
-- This generates indexes
--
select case when ik.key_ordinal =
(select min(ik2.key_ordinal)
from sys.index_columns ik2
where ik2.object_id = ik.object_id
and ik2.index_id = ik.index_id)
then 'create ' +
case when is_unique_constraint = 1 then 'unique '
else ''
end +
'index [' + rtrim(i.name) + ']' + char (10) +
' on [' + rtrim(t.name) + ']' + char (10) +
' ('
else ' ,'
end +
'[' + c.name + ']' +
case when ik.key_ordinal =
(select max(ik2.key_ordinal)
from sys.index_columns ik2
where ik2.object_id = ik.object_id
and ik2.index_id = ik.index_id)
then ')' + char(10) + 'go' + char(10)
else ''
end
from sys.objects t -- table
join #objects o
on o.object_id = t.object_id
join sys.columns c -- columns
on c.object_id = t.object_id
join sys.indexes i -- get index for constraint
on i.object_id = t.object_id
join sys.index_columns ik -- index column and name
on ik.object_id = i.object_id
and ik.index_id = i.index_id
and ik.column_id = c.column_id -- vvv Get the right index
where c.name = index_col(t.name, i.index_id, ik.key_ordinal)
and t.type = 'U'
and i.name <> t.name
and i.name not in
(select c2.name
from sys.objects c2
where c2.parent_object_id = t.object_id
and c2.type in ('PK', 'UQ'))
order by t.name,
i.name,
ik.key_ordinal
-- This generates foreign keys
--
select con.constraint_text as [--constraint_text]
from ((select case when kc.constraint_column_id =
(select min(k2.constraint_column_id)
from sys.foreign_key_columns k2
where k2.constraint_object_id = k.object_id)
then 'alter table [' + #schema + '].[' + rtrim(t.name) + ']' + char(10) +
' add constraint [' + rtrim (k.name) + '] ' + char(10) +
' foreign key ('
else ' ,'
end +
'[' + tc.name + ']' +
case when kc.constraint_column_id =
(select max(k2.constraint_column_id)
from sys.foreign_key_columns k2
where k2.constraint_object_id = k.object_id)
then ')'
else ''
end as constraint_text,
t.name as table_name,
k.name as constraint_name,
kc.constraint_column_id as row_order,
t.object_id
from sys.foreign_keys k
join sys.objects t
on t.object_id = k.parent_object_id
join sys.columns tc
on tc.object_id = t.object_id
join sys.foreign_key_columns kc
on kc.constraint_object_id = k.object_id
and kc.parent_object_id = t.object_id
and kc.parent_column_id = tc.column_id
join sys.objects r
on r.object_id = kc.referenced_object_id
join sys.columns rc
on kc.referenced_object_id = rc.object_id
and kc.referenced_column_id = rc.column_id)
union all
(select case when kc.constraint_column_id =
(select min(k2.constraint_column_id)
from sys.foreign_key_columns k2
where k2.constraint_object_id = k.object_id)
then ' references [' + rtrim(r.name) + ']' + char(10) +
' ('
else ' ,'
end +
'[' + rc.name + ']' +
case when kc.constraint_column_id =
(select max(k2.constraint_column_id)
from sys.foreign_key_columns k2
where k2.constraint_object_id = k.object_id)
then ')' + char(10) + 'go' + char(10)
else ''
end as constraint_text,
t.name as table_name,
k.name as constraint_name,
kc.constraint_column_id + 100 as row_order,
t.object_id
from sys.foreign_keys k
join sys.objects t
on t.object_id = k.parent_object_id
join sys.columns tc
on tc.object_id = t.object_id
join sys.foreign_key_columns kc
on kc.constraint_object_id = k.object_id
and kc.parent_object_id = t.object_id
and kc.parent_column_id = tc.column_id
join sys.objects r
on r.object_id = kc.referenced_object_id
join sys.columns rc
on kc.referenced_object_id = rc.object_id
and kc.referenced_column_id = rc.column_id)) con
join #objects o
on con.object_id = o.object_id
order by con.table_name,
con.constraint_name,
con.row_order

Microsoft SQL Server Database Publishing Wizard is a nice GUI that can script out the structure / data / Procs of a SQL Server 2000/2005 db.
http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en
Hope this helps

A quick google and hop pointed me to a Stored proc that should be able to help you. Look at My code library more specifically the file generate_inserts.txt to see if it can help you.
Not really a tool, but the start of one! :)

For loading and unloading table data you could also use bcp, Integration Services or BULK INSERT (for the loading portion). This article describes a method to invoke bcp from within a stored procedure.

TOAD for Oracle can do it, so I suspect TOAD for SQL Server will be able to too.

Related

SQL Server clone stored procedure including grants

Can I clone a stored procedure including grants to a new name?
create procedure y as clone x
Maybe you can try this SQL Server script:
Declare #sql_create NVarchar(MAX)
Declare #sql_grants NVarchar(MAX)
Declare #sp_name Varchar(MAX)
Declare #sp_new_name Varchar(MAX)
declare #object_id int
set #sp_name = '<YourSPName>'
set #sp_new_name = '<YourSPNewName>'
-- Get SP...
Select #object_id = o.object_id,
#sql_create = Replace(definition, #sp_name, #sp_new_name)
From sys.sql_modules m
inner join sys.objects o on m.object_id = o.object_id
where m.definition like '%' + #sp_name +'%'
and o.type = 'P'
-- Get all permissions
SELECT #sql_grants = COALESCE(#sql_grants + '; ', '') +
(
dp.state_desc + ' ' +
dp.permission_name collate latin1_general_cs_as +
' ON ' + '[' + s.name + ']' + '.' + '[' + Replace(o.name , #sp_name, #sp_new_name) + ']' +
' TO ' + '[' + dpr.name + ']'
)
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
and o.object_id = #object_id
-- Optional
Print (#sql_create) --Note: will cut off at TextWidth!
Print (#sql_grants)
-- Execute queries...
EXEC (#sql_create)
EXEC (#sql_grants)
I hope that helps you!

A short way to make Updates/Deletions to several database's tables

I have an application on vb.net that use a Sql server Database.
I'm using Entity Framework 6.1
The database has a lot's of tables (100+)
-On some tables there's a field "DelDate" (Date)
-On some tables there's a field "DelChilds" (Bit)
Is there a short way to do these operations :
1) Delete all records from all tables that have the DelDate= "01/01/2014"
2) Update the "DelChilds" field on all the records ( for example set to True )
Thank you !
You can write a Dynamic Query using sys.column and sys.tables and execute them in a batch .
You can call Stored Procedure to achieve this functionality using entity framework .
Procedure Code
Create Procedure UpdateDelete #date Date = '01/01/2014'
AS
Begin
Declare #DelQuery Nvarchar(Max),#updatequery Nvarchar(Max),
select #DelQuery = Stuff( (
select ' Delete from ' + t.name + ' where DelDate = ''' + Convert ( varchar,#date,110) + ''';' from sys.columns C JOIN sys.tables t on c.object_id = t.object_id
where C.name = 'DelDate' for XMl Path('')),1,1,'')
select #DelQuery
Exec sp_executeSQL #DelQuery
select #updatequery = Stuff( (
select ' UPDATE ' + t.name + ' SET DelChilds = 1 ;' from sys.columns C JOIN sys.tables t on c.object_id = t.object_id
where C.name = 'DelChilds' for XMl Path('')),1,1,'')
--select #updatequery
Exec sp_executeSQL #updatequery
END
For DelDate
select 'DELETE FROM ' + t.name + ' WHERE DelDate = ''01/01/2014'' ' + Char(13) + 'GO ' from sys.columns C JOIN sys.tables t on c.object_id = t.object_id
where C.name = 'DelDate'
For Delchilds
select 'UPDATE ' + t.name + ' SET DelChilds = 1 ' + Char(13) + 'GO ' from sys.columns C JOIN sys.tables t on c.object_id = t.object_id
where C.name = 'DelChilds'

How can I show the table structure in SQL Server query?

SELECT DateTime, Skill, Name, TimeZone, ID, User, Employee, Leader
FROM t_Agent_Skill_Group_Half_Hour AS t
I need to view the table structure in a query.
For SQL Server, if using a newer version, you can use
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.
Provided that you have a reader for the for the query, you can do something like this:
using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
var schema = reader.GetSchemaTable();
foreach(DataRow row in schema.Rows)
{
Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
}
}
See this article for further details.
sp_help tablename in sql server
desc tablename in oracle
Try this query:
DECLARE #table_name SYSNAME
SELECT #table_name = 'dbo.test_table'
DECLARE
#object_name SYSNAME
, #object_id INT
SELECT
#object_name = '[' + s.name + '].[' + o.name + ']'
, #object_id = o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE s.name + '.' + o.name = #table_name
AND o.[type] = 'U'
AND o.is_ms_shipped = 0
DECLARE #SQL NVARCHAR(MAX) = ''
;WITH index_column AS
(
SELECT
ic.[object_id]
, ic.index_id
, ic.is_descending_key
, ic.is_included_column
, c.name
FROM sys.index_columns ic WITH (NOWAIT)
JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
WHERE ic.[object_id] = #object_id
)
SELECT #SQL = 'CREATE TABLE ' + #object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
SELECT CHAR(9) + ', [' + c.name + '] ' +
CASE WHEN c.is_computed = 1
THEN 'AS ' + cc.[definition]
ELSE UPPER(tp.name) +
CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset')
THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
WHEN tp.name = 'decimal'
THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END +
CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END
END + CHAR(13)
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
WHERE c.[object_id] = #object_id
ORDER BY c.column_id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
+ ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' +
(SELECT STUFF((
SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
FROM sys.index_columns ic WITH (NOWAIT)
JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
WHERE ic.is_included_column = 0
AND ic.[object_id] = k.parent_object_id
AND ic.index_id = k.unique_index_id
FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
+ ')' + CHAR(13)
FROM sys.key_constraints k WITH (NOWAIT)
WHERE k.parent_object_id = #object_id
AND k.[type] = 'PK'), '') + ')' + CHAR(13)
PRINT #SQL
Output:
CREATE TABLE [dbo].[test_table]
(
[WorkOutID] BIGINT NOT NULL IDENTITY(1,1)
, [DateOut] DATETIME NOT NULL
, [EmployeeID] INT NOT NULL
, [IsMainWorkPlace] BIT NOT NULL DEFAULT((1))
, [WorkPlaceUID] UNIQUEIDENTIFIER NULL
, [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL
, [CategoryID] INT NULL
, CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC)
)
Also read this:
http://www.c-sharpcorner.com/UploadFile/67b45a/how-to-generate-a-create-table-script-for-an-existing-table/
On SQL Server 2012, you can use the following stored procedure:
sp_columns '<table name>'
For example, given a database table named users:
sp_columns 'users'
In SQL Server, you can use this query:
USE Database_name
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Table_Name';
And do not forget to replace Database_name and Table_name with the exact names of your database and table names.
For recent versions of SQL Server Management Studio Write the in a query editor and Do "Alt" + "F1"
Try this query:
select *
from (SELECT TABLE_SCHEMA
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='brands')[.brands];
To print a schema, I use jade and do an export to a file of the database then bring it into word to format and print
I was trying 'DESC table_name' but then this worked for me in psql:
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='table_name';
Another way is,
mysql > SHOW CREATE TABLE my_db.my_table;
You should get the table name and create table sql

copy FOREIGN KEY constraints from one DB to other

I have a local db which has FOREIGN KEY constraints.
The live version of this websites DB, does not have any of these FOREIGN KEY constraints.
How can I "copy/paste", import/export ONLY the FOREIGN KEY constraints from one db to the other?
I do NOT want to copy any data, only the constraints.
Thanks
You could use this script I found at http://www.siusic.com/wphchen/how-to-script-out-all-the-foreign-keys-of-a-table-106.html. Replace tablename1 and tablename2 with the list of tables you wish to get the foreign keys for.
select 'ALTER TABLE '+object_name(a.parent_object_id)+
' ADD CONSTRAINT '+ a.name +
' FOREIGN KEY (' + c.name + ') REFERENCES ' +
object_name(b.referenced_object_id) +
' (' + d.name + ')'
from sys.foreign_keys a
join sys.foreign_key_columns b
on a.object_id=b.constraint_object_id
join sys.columns c
on b.parent_column_id = c.column_id
and a.parent_object_id=c.object_id
join sys.columns d
on b.referenced_column_id = d.column_id
and a.referenced_object_id = d.object_id
where object_name(b.referenced_object_id) in
('tablename1','tablename2')
order by c.name
I needed to do something similar, where I needed the same foreign keys on multiple servers, except some had already been added. So I added a "IF NOT EXISTS" check to the beginning of the creation statements:
SELECT N'
IF NOT EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(''' + QUOTENAME(fk.name) + ''')
AND parent_object_id = OBJECT_ID(''' + QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name) +''')
)
BEGIN
ALTER TABLE '
+ QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name)
+ ' ADD CONSTRAINT ' + QUOTENAME(fk.name)
+ ' FOREIGN KEY (' + STUFF((SELECT ',' + QUOTENAME(c.name)
-- get all the columns in the constraint table
FROM sys.columns AS c
INNER JOIN sys.foreign_key_columns AS fkc
ON fkc.parent_column_id = c.column_id
AND fkc.parent_object_id = c.[object_id]
WHERE fkc.constraint_object_id = fk.[object_id]
ORDER BY fkc.constraint_column_id
FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'')
+ ') REFERENCES ' + QUOTENAME(rs.name) + '.' + QUOTENAME(rt.name)
+ '(' + STUFF((SELECT ',' + QUOTENAME(c.name)
-- get all the referenced columns
FROM sys.columns AS c
INNER JOIN sys.foreign_key_columns AS fkc
ON fkc.referenced_column_id = c.column_id
AND fkc.referenced_object_id = c.[object_id]
WHERE fkc.constraint_object_id = fk.[object_id]
ORDER BY fkc.constraint_column_id
FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'') + ')
END'
FROM sys.foreign_keys AS fk
INNER JOIN sys.tables AS rt -- referenced table
ON fk.referenced_object_id = rt.[object_id]
INNER JOIN sys.schemas AS rs
ON rt.[schema_id] = rs.[schema_id]
INNER JOIN sys.tables AS ct -- constraint table
ON fk.parent_object_id = ct.[object_id]
INNER JOIN sys.schemas AS cs
ON ct.[schema_id] = cs.[schema_id]
WHERE rt.is_ms_shipped = 0 AND ct.is_ms_shipped = 0;
If you do not want the "IF NOT EXISTS" checks (they really shouldn't matter), just delete the top 5 lines and add "SELECT N' " right before the "BEGIN", like this:
SELECT N'BEGIN
ALTER TABLE '
+ QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name)
-- I found the core of this query online somewhere and I've been modifying it for some time. Credit to them for putting most of it together...

Renaming all constraint names with user defined names

How do I query the database for all types of constraints such as Primary Key,Foreign Key, Unique Key, and Default Constraint, and rename its system generate name to a name in following format:
PK_ColumnName1_ColumnName2
FK_ColumnName1
UK_ColumnName1_ColumnName2
DF_ColumnName1
SELECT tbl.name TableName, col.name ColName, ck.name ConstraintName, ck.definition ConstraintDefinition ,' exec sp_rename [' +ck.name + '] , [DF_' + col.name + ']' SqlQuery
FROM sys.default_constraints ck
INNER JOIN sys.tables tbl
on ck.parent_object_id = tbl.object_id
INNER JOIN sys.columns col
on tbl.object_id = col.object_id
and ck.parent_column_id = col.column_id
This is for default constraints
use sys.key_constraints
ans sys.foreign_keys
The following code is a little more detailed and it too is specific to default constraints.
select quotename(s.name) + '.' + quotename(o.name) as table_name,
dc.name as default_name,
'DF_' + o.name + '_' + c.name as new_default_name,
'execute sp_rename ''' + quotename(s.name) + '.' + dc.name + ''', ''' + 'DF_' + o.name + '_' + c.name + ''' , ''OBJECT'' -- ' + s.name + '.' + o.name + '' as rename_script
from sys.default_constraints as dc
join sys.objects as o
join sys.schemas as s
on o.schema_id = s.schema_id
on o.object_id = dc.parent_object_id
join sys.columns as c
on o.object_id = c.object_id
and c.column_id = dc.parent_column_id
where dc.name like 'DF[_][_]%[_][_]%[_][_]%' -- DF__AlertType__Creat__10F7245D
and o.type = 'u'
and o.is_ms_shipped = 0
order by s.name,
o.name

Resources