List of Tables names used in MVC Application [duplicate] - c#

I'm looking at creating a basic ORM (purely for fun), and was wondering, is there a way to return the list of tables in a database and also the fields for every table?
Using this, I want to be able to loop through the result set (in C#) and then say for each table in the result set, do this (e.g. use reflection to make a class that will do or contain xyz).
Further to this, what are some good online blogs for SQL Server? I know this question is really about using system SPs and databases in Sql Server, and I am ok with general queries, so I'm interested in some blogs which cover this sort of functionality.
Thanks

Is this what you are looking for:
Using OBJECT CATALOG VIEWS
SELECT T.name AS Table_Name ,
C.name AS Column_Name ,
P.name AS Data_Type ,
C.max_length AS Size ,
CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE T.type_desc = 'USER_TABLE';
Using INFORMATION SCHEMA VIEWS
SELECT TABLE_SCHEMA ,
TABLE_NAME ,
COLUMN_NAME ,
ORDINAL_POSITION ,
COLUMN_DEFAULT ,
DATA_TYPE ,
CHARACTER_MAXIMUM_LENGTH ,
NUMERIC_PRECISION ,
NUMERIC_PRECISION_RADIX ,
NUMERIC_SCALE ,
DATETIME_PRECISION
FROM INFORMATION_SCHEMA.COLUMNS;
Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

Tables ::
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
columns ::
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
or
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'

Get list of all the tables and the fields in database:
Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName'
Get list of all the fields in table:
Select *
From INFORMATION_SCHEMA.COLUMNS
Where TABLE_CATALOG Like 'DatabaseName' And TABLE_NAME Like 'TableName'

I tested a few solutions an found that
Select *
From INFORMATION_SCHEMA.COLUMNS
gives you the column info for your CURRENT/default database.
Select *
From <DBNAME>.INFORMATION_SCHEMA.COLUMNS
, without the < and >, gives you the column info for the database DBNAME.

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

Your other inbuilt friend here is the system sproc SP_HELP.
sample usage ::
sp_help <MyTableName>
It returns a lot more info than you will really need, but at least 90% of your possible requirements will be catered for.

Just throwing this out there - easy to now copy/paste into a word or google doc:
PRINT '<html><body>'
SET NOCOUNT ON
DECLARE #tableName VARCHAR(30)
DECLARE tableCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT T.name AS TableName
FROM sys.objects AS T
WHERE T.type_desc = 'USER_TABLE'
ORDER BY T.name
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO #tableName
WHILE ##FETCH_STATUS = 0 BEGIN
PRINT '<h2>' + #tableName + '</h2>'
PRINT '<pre>'
SELECT LEFT(C.name, 30) AS ColumnName,
LEFT(ISC.DATA_TYPE, 10) AS DataType,
C.max_length AS Size,
CAST(P.precision AS VARCHAR(4)) + '/' + CAST(P.scale AS VARCHAR(4)) AS PrecScale,
CASE WHEN C.is_nullable = 1 THEN 'Null' ELSE 'No Null' END AS [Nullable],
LEFT(ISNULL(ISC.COLUMN_DEFAULT, ' '), 5) AS [Default],
CASE WHEN C.is_identity = 1 THEN 'Identity' ELSE '' END AS [Identity]
FROM sys.objects AS T
JOIN sys.columns AS C ON T.object_id = C.object_id
JOIN sys.types AS P ON C.system_type_id = P.system_type_id
JOIN INFORMATION_SCHEMA.COLUMNS AS ISC ON T.name = ISC.TABLE_NAME AND C.name = ISC.COLUMN_NAME
WHERE T.type_desc = 'USER_TABLE'
AND T.name = #tableName
ORDER BY T.name, ISC.ORDINAL_POSITION
PRINT '</pre>'
FETCH NEXT FROM tableCursor INTO #tableName
END
CLOSE tableCursor
DEALLOCATE tableCursor
SET NOCOUNT OFF
PRINT '</body></html>'

SELECT * FROM INFORMATION_SCHEMA.COLUMNS for get all
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS for get all table name.
Try it on sqlserver,

This will get you all the user created tables:
select * from sysobjects where xtype='U'
To get the cols:
Select * from Information_Schema.Columns Where Table_Name = 'Insert Table Name Here'
Also, I find http://www.sqlservercentral.com/ to be a pretty good db resource.

This will return the database name, table name, column name and the datatype of the column specified by a database parameter:
declare #database nvarchar(25)
set #database = ''
SELECT cu.table_catalog,cu.VIEW_SCHEMA, cu.VIEW_NAME, cu.TABLE_NAME,
cu.COLUMN_NAME,c.DATA_TYPE,c.character_maximum_length
from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE as cu
JOIN INFORMATION_SCHEMA.COLUMNS as c
on cu.TABLE_SCHEMA = c.TABLE_SCHEMA and c.TABLE_CATALOG =
cu.TABLE_CATALOG
and c.TABLE_NAME = cu.TABLE_NAME
and c.COLUMN_NAME = cu.COLUMN_NAME
where cu.TABLE_CATALOG = #database
order by cu.view_name,c.COLUMN_NAME

For MYSQL:
Select *
From INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = "<DatabaseName>"

I found an easy way to fetch the details of Tables and columns of a particular DB using SQL developer.
Select *FROM USER_TAB_COLUMNS

in a Microsoft SQL Server you can use this:
declare #sql2 nvarchar(2000)
set #sql2 ='
use ?
if ( db_name(db_id()) not in (''master'',''tempdb'',''model'',''msdb'',''SSISDB'') )
begin
select
db_name() as db,
SS.name as schemaname,
SO.name tablename,
SC.name columnname,
ST.name type,
case when ST.name in (''nvarchar'', ''nchar'')
then convert(varchar(10), ( SC.max_length / 2 ))
when ST.name in (''char'', ''varchar'')
then convert(varchar(10), SC.max_length)
else null
end as length,
case when SC.is_nullable = 0 then ''No'' when SC.is_nullable = 1 then ''Yes'' else null end as nullable,
isnull(SC.column_id,0) as col_number
from sys.objects SO
join sys.schemas SS
on SS.schema_id = SO.schema_id
join sys.columns SC
on SO.object_id = SC.object_id
left join sys.types ST
on SC.user_type_id = ST.user_type_id and SC.system_type_id = ST.system_type_id
where SO.is_ms_shipped = 0
end
'
exec sp_msforeachdb #command1 = #sql2
this shows you all tables and columns ( and their definition ) from all userdefined databases.

Related

Is it possible to update bunch of different Tables in DB with the same modification to all?

I want to duplicate all my tables in SQL Server, all table names would have had "temp" added at the beginning. And all of them would have had added an extra column (the same to all). I don't need whole code, just general idea how to do it.
A straightforward way to go:
You need to fetch the table names from your database (probably using INFORMATION_SCHEMA.TABLES).
For each of those tables from step 1, you need to generate a corresponding SELECT ... INTO statement.
You need to execute each generated SQL statement from step 2.
You already have a solution with a cursor. This is one without a cursor:
DECLARE #script VARCHAR(MAX) = '';
SELECT #script = #script + 'SELECT * INTO [temp'+ TABLE_NAME +'] FROM [' + TABLE_NAME + '];' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.TABLES
EXEC (#script);
Remark: The CHAR(13) + CHAR(10) is not necessary; just added for readability if you want to check the script first (using PRINT instead EXEC).
Edit:
An additional question in the comments to add a checksum value in the resulting tables could be done as follows:
DECLARE #script VARCHAR(MAX) = '';
SELECT #script = #script + 'SELECT CHECKSUM(*) AS [__checksum], * INTO [temp'+ TABLE_NAME +'] FROM [' + TABLE_NAME + '];' + CHAR(13) + CHAR(10) FROM INFORMATION_SCHEMA.TABLES
EXEC (#script);
Using HASHBYTES instead of CHECKSUM is probably better, but it accepts only two parameters: the hash algorithm and a single value to hash. So in that case, you probably need to pass a string value by manually concatenating all the fields of your tables, and that may be somewhat troublesome to add in a dynamic query like mine. It would probably result in something more complex than just three lines...
Well, something like this, actually:
DECLARE #script NVARCHAR(MAX) = N'';
WITH
[Columns] AS
(
SELECT
TABLE_NAME AS [TableName],
COLUMN_NAME AS [ColumnName],
ROW_NUMBER() OVER (PARTITION BY TABLE_NAME ORDER BY ORDINAL_POSITION) AS [ColSeq]
FROM
INFORMATION_SCHEMA.COLUMNS
),
[Tables] AS
(
SELECT
[TableName],
CAST(N'[' + [ColumnName] + N']' AS NVARCHAR(MAX)) AS [ColumnList],
[ColSeq]
FROM
[Columns] AS C
WHERE
[ColSeq] = (SELECT MAX([ColSeq])
FROM [Columns]
WHERE [TableName] = C.[TableName])
UNION ALL
SELECT T.[TableName], N'[' + C.[ColumnName] + N'], ' + T.[ColumnList], C.[ColSeq]
FROM
[Tables] AS T
INNER JOIN [Columns] AS C ON C.[TableName] = T.[TableName] AND C.[ColSeq] = T.[ColSeq] - 1
)
SELECT #script = #script + N'SELECT HASHBYTES(''md5'', CONCAT(N'''', ' + [ColumnList] + N')) AS [__checksum], * INTO [temp' + [TableName] + N'] FROM [' + [TableName] + N'];' + NCHAR(13) + NCHAR(10)
FROM [Tables]
WHERE [ColSeq] = 1;
EXEC (#script);
Remarks:
In the recursive CTE [Tables], which is used for concatenating the column names of each table in a comma-separated string value, I started at the last column and moved backwards to ease the filter condition in my main query.
I added an additional first parameter N'' to the CONCAT calls in the resulting #script contents, since the CONCAT function requires at least 2 arguments, which would be troublesome in this case when processing tables with just one column.
In this case, despite the somewhat worse performance, it might be clearer and easier to fall back to using a cursor, like #HasanMahmood suggested in his answer...
try this code:
get all the table name form information schema and run a dynamic sql to create tables
DECLARE #script varchar(max)
DECLARE db_cursor CURSOR FOR
SELECT script = 'Select * Into [temp'+ TABLE_NAME +'] From ' + QUOTENAME(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #script
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC(#script)
--PRINT #script
FETCH NEXT FROM db_cursor INTO #script
END
CLOSE db_cursor
DEALLOCATE db_cursor

Stored Procedure giving different result on same database with same argument

I have a stored procedure which gives different result in only a specific case.
When I call it from SQL Server Management Studio 2008 R2, it gives me 0 as output.
When I call it from C# class file. It gives me 1 as output.
I am using edmx file, and it is updated for sure.
The call is something like below from SSMS [SQL Server Management Studio]
exec proc_GetPrimaryKeyUsageCount 62, 'tblFormula'
This gives output as 0
The same stored procedure is called from C# file is like below
_db.GetPrimaryKeyUsageCount(62, "tblFormula");
This gives output as 1
The stored procedure is
CREATE PROCEDURE proc_GetPrimaryKeyUsageCount (
#PrimaryKeyColumnId INT
,#PrimaryKeyTable NVARCHAR(max)
--,#Response INT OUTPUT
)
AS
BEGIN
DECLARE #counter INT
DECLARE #sqlCommand NVARCHAR(max)
DECLARE #ForeignKey TABLE (
child_table VARCHAR(max)
,child_fk_column VARCHAR(max)
)
DECLARE #child_table VARCHAR(max)
DECLARE #child_fk_column VARCHAR(max)
SET #counter = 0
INSERT INTO #ForeignKey
SELECT child_table = c.TABLE_NAME
,child_fk_column = c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'IsDeleted'
AND TABLE_SCHEMA = p.TABLE_SCHEMA
AND TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
DECLARE db_cursor CURSOR
FOR
SELECT child_table
,child_fk_column
FROM #ForeignKey
OPEN db_cursor
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'select count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
SET #sqlCommand = 'select #cnt=count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
EXEC sp_executesql #sqlCommand
,N'#cnt int OUTPUT'
,#cnt = #counter OUTPUT
IF #counter > 0
BREAK
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
END
SELECT #counter AS [PrimaryKeyUsageCount]
END
1st argument is Id of the primary key and 2nd argument is the name of the table having that primary key.
The Procedure returns the count of the usage of primary key in other tables in same database. If it finds even 1 occurrence, it will return that count otherwise 0.
If anything extra is needed please do let me know.
There are couple of mistakes, which could cause the problem.
The INSERT should be like that:
INSERT INTO #ForeignKey
SELECT c.TABLE_NAME,c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS AS isc
WHERE isc.COLUMN_NAME = 'IsDeleted'
AND isc.TABLE_SCHEMA = p.TABLE_SCHEMA
AND isc.TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
After cursor loop shoud be:
CLOSE db_cursor
DEALLOCATE db_cursor

Returning only the column names from a SELECT statement

This is just a lazy thought. I have a table with about 9 columns names. Is there any way I can use SQL statement to return only the Column names? The normal way is to write out my column names from
SELECT * FROM tableName;
statement but was wondering if I can get the column names with SQL statement.
Any Ideas would be appreciated.
Thanks You!
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tableName' AND TABLE_SCHEMA='dbo'
Should do it
SET FMTONLY ON
SELECT * FROM tablename
Open you Microsoft SQL Server Management Studio, in New Query, Just type your Table name and select it and then press ALT + F1 Key, it will give all details about table
You can query the syscolumns table for table column metadata.
SELECT [name] AS [Column Name]
FROM syscolumns
WHERE id = (SELECT id FROM sysobjects WHERE [Name] = 'TableName')
See this image that query return values
Referred from : How can I get column names from a table in Oracle?
and another one way
select column_name,* from information_schema.columns
where table_name = 'YourTableName'
order by ordinal_position
Using SQL Server xml raw you get the column names from any sql query. Replace 'select top 1 * from [TABLENAME]' from the example below. Query must return at least 1 row of data and remember to use top 1.
declare #t1 table (x xml)
declare #t2 table (x xml)
declare #t3 table (x xml)
insert into #t1 select cast( (select top 1 * from [TABLENAME] for xml raw) as xml)
insert into #t2 select y.r.query('.') from #t1 cross apply x.nodes('/row') as y(r)
insert into #t3 select t2.n.value('local-name(.)', 'varchar(max)') from #t2 t cross apply x.nodes('//#*') as t2(n)
select replace (convert (nvarchar, x),'_x0020_', ' ') from #t3
Try following SQL statement to get column name.
SELECT column_name
FROM information_schema.columns
WHERE TABLE_NAME='tableName'

Must declare the scalar variable "#dom"

This is a bit confusing because it worked before and I added 1 little change and I get this error message in my web application. (I do have other cases, I just took out the other cases for simplicity)
Original code that worked before:
ALTER PROCEDURE [dbo].[GetRoles]
(#reportid Decimal, #dom varchar(10))
AS
DECLARE #sql varchar(2000)
SELECT #sql =
Case #reportid
WHEN 1 THEN
'select u.id as userId, u.domain, u.isAdmin, u.email, u.canReport, a.[site], a.bldgNum, a.dataCenterNum, l.shortName, l.[description], a.canApprove, a.canComplete
from locAdmin a
inner join location l on (a.site=l.site and a.bldgNum = l.bldgNum and a.dataCenterNum = l.dataCenterNum)
right outer join [user] u on u.id=a.userId and u.domain=a.domain
where u.isAdmin = 1'
End
EXEC (#sql)
The only change I did was adding
and u.domain = #dom'
after where u.isAdmin = 1' at the end so it looks like this
where u.isAdmin = 1 and u.domain = #dom'
You need to add #dom as a parameter when you execute your dynamic SQL.
Replace EXEC (#sql) with exec sp_executesql #sql, N'#dom varchar(10)', #dom and change DECLARE #sql varchar(2000) to DECLARE #sql nvarchar(2000).
You don't need dynamic SQL to to this write this query.
Please do it like this:
ALTER PROCEDURE [dbo].[GetRoles]
(
#reportid Decimal,
#dom varchar(10)
)
AS
select u.id as userId, u.domain, u.isAdmin, u.email, u.canReport,
a.[site], a.bldgNum, a.dataCenterNum,
l.shortName, l.[description],
a.canApprove, a.canComplete
from locAdmin a
inner join location l
on a.site=l.site and a.bldgNum = l.bldgNum and a.dataCenterNum = l.dataCenterNum
right outer join [user] u
on u.id=a.userId and u.domain=a.domain
where u.isAdmin = 1 and u.domain = #dom and #reportid = 1
You need to actually add the value of the variable to your dynamic SQL:
'THE REST OF YOUR QUERY
where u.isAdmin = 1 and u.domain = ''' + #dom + ''''
This is because your dynamic SQL is another SQL statement that you are going to execute, and therefore doesn't know about the parameter #dom in your original statement.

How to get the constraints on a table

By constraints I mean checks, not nulls, primary key constraint, foreign key constraint
What SQL query to use
Visual Studio 2008 / SQL Server 2005 Express
Like for example to get table names
commandString = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
So what to get constraints.
not nulls is not a constraint, you can check for that in information_schema.columns
for constraints
select *
from information_schema.table_constraints
for columns that don't allow nulls
select *
from information_schema.columns
where is_nullable = 'NO'
You can use the sys.objects table to get this info, check this query to get all Constraints of an table .
SELECT OBJECT_NAME(OBJECT_ID) AS [Constraint],SCHEMA_NAME(schema_id) AS [Schema],
OBJECT_NAME(parent_object_id) AS [Table],
type_desc AS [Type] FROM sys.objects
WHERE 1=1
AND OBJECT_NAME(parent_object_id)='YOURTABLENAME'
AND type_desc LIKE '%CONSTRAINT'
Give this a try, it is a little query I've put together, and should get you going in the right direction. You can remove the comments as necessary to filter for the specific schema/table/column that you want.
/*Run a query like the listed below, from it you can see:
+ schema name
+ table/view name
+ table type (like: SYSTEM_TABLE, VIEW, SQL_TABLE_VALUED_FUNCTION, USER_TABLE, SQL_INLINE_TABLE_VALUED_FUNCTION, INTERNAL_TABLE)
+ column name
+ column data type (including length, precision, etc)
+ Nullability
+ identity (seed, increment, and current value)
+ check constraint definition
+ computed column definition
+ complete index and primary key info, every index/PK that this column is contained in, includes index type (unique/clustered/PK etc) as well as all index/pk columns concatenated together, including covering columns
Needs SQL Server 2005+ to run:
*/
--DECLARE #SchemaNameSearch sysname
-- ,#TableNameSearch sysname
-- ,#ColumnNameSearch sysname
--SELECT #SchemaNameSearch ='YourSchemaName'
-- ,#TableNameSearch ='YourTableName'
-- ,#ColumnNameSearch ='YourColumnName'
;WITH AllIndexes AS
(
SELECT
s.name+'.'+t.name AS TableName
,xx.name AS IndexName
,'['
+CASE WHEN xx.is_unique=1 THEN 'UNIQUE ' ELSE '' END
+xx.type_desc
+CASE WHEN xx.is_primary_key=1 THEN ' PRIMARY KEY' ELSE '' END
+ISNULL(
' ('
+STUFF(
(SELECT
', '+c.Name
FROM sys.objects o
LEFT OUTER JOIN sys.indexes x ON o.object_id=x.object_id
LEFT OUTER JOIN sys.index_columns xc ON o.object_id=xc.object_id AND x.index_id=xc.index_id
LEFT OUTER JOIN sys.columns c ON o.object_id=c.object_id AND c.column_id=xc.column_id
WHERE oo.object_id=o.object_id AND xc.column_id IS NOT NULL
AND xx.index_id=x.index_id AND xc.is_included_column=0
--
--REMOVE comments to filter the query
--AND o.Name=#TableNameSearch
--
ORDER BY o.object_ID,xc.key_ordinal
FOR XML PATH('')
)
,1,2, ''
)
+')'
,''
)
+ISNULL(
' INCLUDE ('
+STUFF(
(SELECT
', '+c.Name
FROM sys.objects o
LEFT OUTER JOIN sys.indexes x ON o.object_id=x.object_id
LEFT OUTER JOIN sys.index_columns xc ON o.object_id=xc.object_id AND x.index_id=xc.index_id
LEFT OUTER JOIN sys.columns c ON o.object_id=c.object_id AND c.column_id=xc.column_id
WHERE oo.object_id=o.object_id AND xc.column_id IS NOT NULL
AND xx.index_id=x.index_id AND xc.is_included_column=1
--
--REMOVE comments to filter the query
--AND o.Name=#TableNameSearch
--
ORDER BY o.object_ID,xc.key_ordinal
FOR XML PATH('')
)
,1,2, ''
)
+')'
,''
)
+']' AS IndexInfo
,cc.object_id,cc.column_id,xx.is_primary_key
FROM sys.objects oo
INNER JOIN sys.tables t ON oo.object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
LEFT OUTER JOIN sys.indexes xx ON oo.object_id=xx.object_id
LEFT OUTER JOIN sys.index_columns xxc ON oo.object_id=xxc.object_id AND xx.index_id=xxc.index_id
LEFT OUTER JOIN sys.columns cc ON oo.object_id=cc.object_id AND cc.column_id=xxc.column_id
--
--REMOVE comments to filter the query
--WHERE s.name =#SchemaNameSearch
-- AND oo.Name=#TableNameSearch
-- AND s.name=#ColumnNameSearch
--
)
SELECT
sh.name+'.'+o.name AS ObjectName
,o.type_desc AS ObjectType
,s.name as ColumnName
,CASE
WHEN t.name IN ('char','varchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END+')'
WHEN t.name IN ('nvarchar','nchar') THEN t.name+'('+CASE WHEN s.max_length<0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length/2) END+')'
WHEN t.name IN ('numeric') THEN t.name+'('+CONVERT(varchar(10),s.precision)+','+CONVERT(varchar(10),s.scale)+')'
ELSE t.name
END AS DataType
,CASE
WHEN s.is_nullable=1 THEN 'NULL'
ELSE 'NOT NULL'
END AS Nullable
,CASE
WHEN All_IXs.object_id IS NOT NULL THEN All_IXs.IndexInfo
ELSE NULL
END AS IndexInfo
,CASE
WHEN ic.column_id IS NULL THEN ''
ELSE ' identity('+ISNULL(CONVERT(varchar(10),ic.seed_value),'')+','+ISNULL(CONVERT(varchar(10),ic.increment_value),'')+')='+ISNULL(CONVERT(varchar(10),ic.last_value),'null')
END
+CASE
WHEN sc.column_id IS NULL THEN ''
ELSE ' computed('+ISNULL(sc.definition,'')+')'
END
+CASE
WHEN cc.object_id IS NULL THEN ''
ELSE ' check('+ISNULL(cc.definition,'')+')'
END
AS MiscInfo
FROM sys.objects o
INNER JOIN sys.schemas sh on o.schema_id=sh.schema_id
INNER JOIN sys.columns s ON o.object_id=s.object_id
INNER JOIN sys.types t ON s.system_type_id=t.system_type_id and t.is_user_defined=0
LEFT OUTER JOIN sys.identity_columns ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
LEFT OUTER JOIN sys.computed_columns sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
LEFT OUTER JOIN sys.indexes x ON o.object_id=x.object_id AND x.is_primary_key=1
LEFT OUTER JOIN sys.index_columns xc ON o.object_id=xc.object_id AND x.index_id=xc.index_id AND s.column_id=xc.column_id
LEFT OUTER JOIN (SELECT --build the concatenated PK here
oo.object_id,ss.column_id
,STUFF(
(
SELECT
', '+IndexInfo
FROM AllIndexes i
WHERE oo.object_id=i.object_id AND ss.column_id=i.column_id
ORDER BY i.object_ID ASC,i.is_primary_key DESC,i.column_id ASC
FOR XML PATH('')
)
,1,2, ''
) AS IndexInfo
FROM sys.objects oo
INNER JOIN sys.columns ss ON oo.object_id=ss.object_id
--
--REMOVE comments to filter the query
--WHERE oo.Name=#TableNameSearch
--
) All_IXs ON o.object_id=All_IXs.object_id AND s.column_id=All_IXs.column_id
--
--REMOVE comments to filter the query
--WHERE sh.name =#SchemaNameSearch
-- AND o.Name=#TableNameSearch
-- AND s.name=#ColumnNameSearch
--
ORDER BY sh.name+'.'+o.name,s.column_id
As well as the other methods, you can use sp_help (ALT-F1 by default)
CREATE TABLE testTable2
(
test int
)
ALTER TABLE testTable2
ADD CHECK (test>40)
sp_help testTable2
will yield the constraint and the conditions. This is also shows FKs, UKs, etc.
this gives you Name of the constraint , type and table [MS-SQL 2000]
Select s.name,
(Case
when s.xtype='PK' then 'PRIMARY KEY'
when s.xtype='F' then 'FOREIGN KEY'
when s.xtype='D' then 'DEFAULT' -- add case for others if you wish
else s.xtype
end) as [Constraint Type],
Tab.[Name] as [Table Name]--,Col.[Name] As [Column Name]
from sysobjects as s
Inner Join (Select [Name],[ID] From SysObjects Where XType = 'U') As Tab
On Tab.[ID] = s.[Parent_Obj]
Inner Join sysconstraints
On sysconstraints.Constid = s.[ID]

Categories

Resources