简体   繁体   English

SQL Server:如果是bigint,请更改数据类型

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

I am trying to change data type for a colyumn from bigint to int. 我正在尝试将colyumn的数据类型从bigint更改为int。 I know how to do an alter statement and how to find which data type is currently assigned to it: 我知道如何做一个alter语句,以及如何找到当前分配给它的数据类型:

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. 但是我无法在if语句中弄清楚该怎么做。 I only need to change the datatype IF it is currently bigint. 如果当前为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. 无需使用IF条件,在Where子句中添加BIGINT过滤器。 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 如果数据类型不是BIGINT则没有任何执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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