sql server : get default value of a column

goucqfw6  于 2023-03-11  发布在  SQL Server
关注(0)|答案(5)|浏览(192)

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

oprakyz7

oprakyz71#

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.

zpgglvta

zpgglvta2#

Use

Select * From INFORMATION_SCHEMA.COLUMNS

there is a column called COLUMN_DEFAULT

kupeojn6

kupeojn64#

'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'
krcsximq

krcsximq5#

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'

相关问题