简体   繁体   English

如何在SQL Server中将int转换或转换为字符串

[英]How to convert or cast int to string in SQL Server

Looking at a column that holds last 4 of someone's SSN and the column was originally created as an int datatype. 查看包含某人的SSN的后4位的列,该列最初是作为int数据类型创建的。 Now SSN that begin with 0 get registered as 0 on the database. 现在,以0开头的SSN在数据库中注册为0。

How can I convert the column and it's information from an int into a string for future proof? 如何将列及其信息从int转换为字符串以供将来证明?

You should convert. 您应该转换。 CONVERT(VARCHAR(4), your_col)

If you specifically want zero-padded numbers, then the simplest solution is format() : 如果您特别想要零填充数字,那么最简单的解决方案是format()

select format(123, '0000')

If you want to fix the table, then do: 如果要修复表,请执行以下操作:

alter table t alter column ssn4 char(4);  -- there are always four digits

Then update the value to get the leading zeros: 然后更新该值以获得前导零:

update t
    ssn4 = format(convert(int, ssn4), '0000');

Or, if you just want downstream users to have the string, you can use a computed column: 或者,如果只希望下游用户拥有该字符串,则可以使用计算列:

alter table t
    add ssn4_str as (format(ssn4, '0000'));

如果要添加前导零,请使用:

SELECT RIGHT('0000'+ISNULL(SSN,''),4)

First thing never store SSN or Zip Code as any numeric type. 第一件事永远不要将SSN或邮政编码存储为任何数字类型。 Second you should fix the underlying table structure not rely on a conversion...but if you're in a jam this is an example of a case statement that will help you. 其次,您应该修复基础表结构,而不要依赖于转换...但是,如果遇到麻烦,这是一个可以帮助您的case语句示例。

IF OBJECT_ID('tempdb..#t') IS NOT NULL
    BEGIN
        DROP TABLE #t
    END
GO
CREATE TABLE #t(
    LastFourSSN INT
)

INSERT INTO #t(LastFourSSN)
VALUES('0123'),('1234')

SELECT LastFourSSN --strips leading zero
FROM #t

SELECT -- adds leading zero to anything less than four charaters
    CASE 
        WHEN LEN(LastFourSSN) < 4 
        THEN '0' + CAST(LastFourSSN AS VARCHAR(3)) 
        ELSE CAST(LastFourSSN AS VARCHAR(4)) 
    END LastFourSSN 
FROM #t

If you are looking for converting values in the column for your purpose to use in application, you can use this following- 如果您希望在列中转换值以供在应用程序中使用,可以使用以下命令:

SELECT CAST(your_column AS VARCHAR(100))
--VARCHAR length based on your data

But if you are looking for change data type of your database column directly, you can try this- 但是,如果您要直接查找数据库列的更改数据类型,则可以尝试以下操作-

ALTER TABLE TableName 
ALTER COLUMN your_column VARCHAR(200) NULL
--NULL or NOT NULL based on the data already stored in database

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

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