Concat在第二列值SQL中带有前导零的两列

时间:2015-09-16 20:26:35

标签: sql sql-server

我正在尝试使用特定格式的两列来连接第二列值的值。第二列值应该在" 0000"格式。 我有这样的当前查询

SELECT 
     ISNULL(BatchID,'')+ISNULL(UID,'') as BatchIDUID 
FROM 
     myTable 
WHERE 
     id=249

给我输出

1509161               //BatchID = 150961 and UID = 1

它的格式应为

1509160001            //BatchID = 150961 and UID = 1
1509160022            //BatchID = 150961 and UID = 22
1509160333            //BatchID = 150961 and UID = 333
1509164444            //BatchID = 150961 and UID = 4444

2 个答案:

答案 0 :(得分:3)

使用RIGHT

SELECT 
     ISNULL(BatchID,'')+ISNULL(RIGHT('0000' + UID, 4),'') as BatchIDUID 
FROM myTable 
WHERE  id=249;

一般方法:

DECLARE @pad INT = 4;
SELECT RIGHT(REPLICATE('0', @pad) + /* column/variable */, @pad);

答案 1 :(得分:1)

作为一个注释,您可以使用算术执行此操作,而不是将值转换为字符串:

select COALESCE(BatchId, 0) * 10000 + COALESCE(UId, 0)

然后您可以将其转换为字符串:

select CAST(COALESCE(BatchId, 0) * 10000 + COALESCE(UId, 0) as VARCHAR(10))

这适用于您的值,它们适合整数。但是,您可以使用小数来支持更长的值:

select COALESCE(CAST(BatchId as DECIMAL(20, 0)), 0) * 10000 + COALESCE(UId, 0)