简体   繁体   中英

SQL-Server: change data type IF it's a bigint

I am trying to change data type for a colyumn from bigint to int. I know how to do an alter statement and how to find which data type is currently assigned to it:

SELECT data_type
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table_Name' AND COLUMN_NAME = 'ColumnName'

However I can't figure out how to do it in an if statement. I only need to change the datatype IF it is currently bigint.

The table has no rows in it so moving data is not an issue at the moment.

I'd really appreciate the help, thanks in advance!

No need to use IF condition add the BIGINT filter in Where clause. Try something like this

DECLARE @sql VARCHAR(8000)=''

SET @sql = (SELECT 'alter table ' + Quotename(TABLE_NAME)
                   + ' alter column ' + Quotename(COLUMN_NAME)
                   + ' int ' + CASE WHEN IS_NULLABLE = 'yes' THEN ' NULL ' ELSE ' NOT NULL ' END
            FROM   INFORMATION_SCHEMA.COLUMNS
            WHERE  TABLE_NAME = 'Table_Name'
                   AND COLUMN_NAME = 'ColumnName'
                   AND DATA_TYPE = 'bigint') 

Exec (@sql)

If the datatype is not BIGINT then there will be nothing to execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM