Reputation: 245
I execute a select to get the structure of a table. I want to get info about the columns like its name or if it's null or if it's primary key.. I do something like this
....sys.columns c...
c.precision,
c.scale,
c.is_nullable as isnullable,
c.default_object_id as columndefault,
c.is_computed as iscomputed,
but for default value i get the id..something like 454545454 but i want to get the value "xxxx". What is the table to search or what is the function to convert that id to the value. Thanks
Upvotes: 8
Views: 20426
Reputation: 173
If you want to focus on the DEFAULT values, the built-in function GETDEFAULT can help, but as long as it requires to use numbers (you can't use a DB_ID(), a column or even a variable with the function) to escape this I made a procedure:
CREATE OR ALTER PROC PRC_GETDEFAULT(@TABLE_NAME VARCHAR(200)=NULL) AS BEGIN
SELECT
PK=ROW_NUMBER()OVER(ORDER BY COLUMN_ID)
,COLUMN_NAME = C.NAME
,DEFAULT_NAME = DC.NAME
,COLUMN_ID
,DEFAULT_OBJECT_ID = DC.OBJECT_ID
,DC.DEFINITION
,DB_ID=CONVERT(INT,DB_ID())
,DEFAULT_VALUE = CONVERT(SQL_VARIANT, NULL)
INTO #GET_DEFAULT
FROM SYS.DEFAULT_CONSTRAINTS DC
JOIN SYS.COLUMNS C ON DC.PARENT_OBJECT_ID = C.OBJECT_ID AND DC.PARENT_COLUMN_ID = C.COLUMN_ID
WHERE PARENT_OBJECT_ID = OBJECT_ID(@TABLE_NAME)
DECLARE @END INT = @@ROWCOUNT
DECLARE @I INT = 0
DECLARE @QORIGINAL VARCHAR(MAX) = '
UPDATE #GET_DEFAULT
SET DEFAULT_VALUE = GETDEFAULT(' + LTRIM(DB_ID()) + ','
DECLARE @QEXECUTE VARCHAR(MAX)
WHILE @I < @END BEGIN
SET @I += 1
SELECT @QEXECUTE = CONCAT(@QORIGINAL, DEFAULT_OBJECT_ID, ')
WHERE PK = ', @I)
FROM #GET_DEFAULT
WHERE PK = @I
EXEC(@QEXECUTE)
END
SELECT
*
FROM #GET_DEFAULT
END
This procedure only needs the table name and returns all the columns from the table that have default values and the active default values, example:
exec PRC_GETDEFAULT TB_EXAMPLE
--or
exec PRC_GETDEFAULT 'DBO.TB_EXAMPLE'
Upvotes: 0
Reputation: 11
'bills' is an example table
select
COLUMN_DEFAULT --default
,IS_NULLABLE -- is nullable
,NUMERIC_PRECISION --number of digits (binary or decimal depending on radix)
,NUMERIC_PRECISION_RADIX --decimal places
,NUMERIC_SCALE --number of digits to right of decimal point
,COLUMNPROPERTY(OBJECT_ID('bills'),COLUMN_NAME,'Iscomputed') AS ISCOMPUTED --is computed
from INFORMATION_SCHEMA.columns where TABLE_name='bills'
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME='bills' and CONSTRAINT_TYPE='PRIMARY KEY'
Upvotes: 1
Reputation: 43974
Use
Select * From INFORMATION_SCHEMA.COLUMNS
there is a column called COLUMN_DEFAULT
Upvotes: 7
Reputation: 309
The property you want is called "cdefault".
http://sql-server-performance.com/Community/forums/p/20588/114944.aspx
Upvotes: 1
Reputation: 147224
You can do this (done a SELECT * just so you can see all the info available):
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE....
This includes a "COLUMN_DEFAULT" column in the resultset.
Upvotes: 11