Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何将零添加到id len中的基本nvarchar中_Sql Server_Tsql - Fatal编程技术网

Sql server 如何将零添加到id len中的基本nvarchar中

Sql server 如何将零添加到id len中的基本nvarchar中,sql-server,tsql,Sql Server,Tsql,这个想法是当ID=1,列代码001和ID=10,列代码010,最后我希望列代码得到ID的数据,因为这个原因是else create table test( Id int, Code as case when len(Id)=1 then '00'+Id when len(Id)=2 then '0'+Id Else Id End ); 您需要将code作为字符串。最简单的方法是使用concat(): 或者更简单地说: code as (right(concat('000', id), 3)

这个想法是当ID=1,列代码001和ID=10,列代码010,最后我希望列代码得到ID的数据,因为这个原因是else

create table test(
Id int,
Code as case when len(Id)=1 then '00'+Id when len(Id)=2 then '0'+Id Else Id End 
);


您需要将
code
作为字符串。最简单的方法是使用
concat()

或者更简单地说:

code as (right(concat('000', id), 3))
当然,这个版本不处理大于999的
id
值。

你好,阿尔贝托·莫拉。 您可以使用Function Right+concat,因为使用LEFT+concat无法获得正确的结果:

   RIGHT(CONCAT('00',cast (Id AS NVARCHAR(MAX))),3)
或使用函数格式:

  FORMAT(Id,'000')

如果您使用的是支持它的SQL Server版本,
format()
函数为您提供了:


选择格式(1,'D3')

现在我有了一个触发器,但我在3个表中使用了相同的代码code是一个nvarcharBro,谢谢,现在我不再用triggers@HABO . . . 接得好。谢谢。关于这个函数,在你回答之前我已经写过了。
  FORMAT(Id,'000')