Sql server 表中前导为零的T-SQL插入编号
我需要在我的表中插入一个数字Sql server 表中前导为零的T-SQL插入编号,sql-server,database,tsql,Sql Server,Database,Tsql,我需要在我的表中插入一个数字0000128,但它将此数字视为128,我也尝试将类型从int更改为varchar,但没有区别 有可能做到这一点吗?没有带前导零的数字,只有带前导零的数字的文本表示。存储为varchar应该可以 DECLARE @T TABLE ( V VARCHAR(10)); INSERT INTO @T VALUES ('0000128'); SELECT * FROM @T 您必须在进行数值转换的过程中丢失前导零。我以前在执行ETL时遇到过这个问题。
0000128
,但它将此数字视为128
,我也尝试将类型从int
更改为varchar
,但没有区别
有可能做到这一点吗?没有带前导零的数字,只有带前导零的数字的文本表示。存储为
varchar
应该可以
DECLARE @T TABLE (
V VARCHAR(10));
INSERT INTO @T
VALUES ('0000128');
SELECT *
FROM @T
您必须在进行数值转换的过程中丢失前导零。我以前在执行ETL时遇到过这个问题。我就是这样解决的
-- declare and assign
-- this could be from anywhere
declare @int_NUMBER int = 128
-- show the original
select @int_NUMBER
-- steps:
-- first: cast the number as a varchar
-- second: create a string of zeros. The number of zeros should be equal to the max size of this "number".
-- In this example, the max size this "number" is 7 places.
-- third: concat the leading zeros in front of the varchar of the number
-- forth: take the number of max places from the right
-- this way you will always get the proper amount of leading zeros
select right('0000000' + cast(@int_NUMBER as varchar(10)),7)
结果:
128 (1行受影响)
0000128
(1行受影响)PIN号码和电话号码都是常用术语中称为“数字”但有重要前导零的示例。我不认为这是一个有用的答案。这就是问题所在,我不能失去这个零,因为它是公司分配的号码,有时它会是4个零,而另一次是2个,所以我需要保存它,以便以后恢复它。就像我之前说的,我试过使用varchar,但没有work@Maggie因此,只需确保它始终被视为一个字符串。然后
000012
和0012
将不会以12
结束。