SQL字段长度

时间:2015-05-14 09:46:19

标签: sql sql-server tsql

SELECT @list = (seg_tag+
                '01'+ 
                CAST(LEN(ID_Type) AS NVARCHAR)+
                ID_Type+
                '02'+
                CAST(LEN(IDNumber) AS NVARCHAR)+
                IDNumber)
FROM #TEMP_TABLE_ID

在上面的查询中,我需要做什么,以便在打印列表时,长度(如果是单个数字)出现零? 防爆。

04 for 4
09 for 9
14 for 14

#TEMP_TABLE_ID中的示例数据:

seg_tag | ID_Type | IDNumber
--------+---------+----------
PN03    | paras   | narang

结果应如下所示:PN03015paras026narang

2 个答案:

答案 0 :(得分:1)

SELECT @list = (RIGHT('0'+seg_tag,2)+
            '01'+ 
            RIGHT('0'+CAST(LEN(ID_Type) AS NVARCHAR),2)+
            RIGHT('0'+ID_Type,2)+
            '02'+
            RIGHT('0'+CAST(LEN(IDNumber) AS NVARCHAR),2)+
            RIGHT('0'+IDNumber,2))
FROM #TEMP_TABLE_ID

答案 1 :(得分:0)

你需要这个:

SELECT @list = seg_tag 
             + '01' + RIGHT('0' + CAST(LEN(ID_Type) AS varchar), 2) 
             + ID_Type  
             + '02' + RIGHT('0' + CAST(LEN(IDNumber) AS varchar), 2)
             + IDNumber
FROM #TEMP_TABLE_ID

或者

SELECT @list = seg_tag 
             + '01' 
             + CASE WHEN LEN(ID_Type) < 10 THEN '0' ELSE '' END + 
             + CAST(LEN(ID_Type) AS varchar)
             + ID_Type  
             + '02'
             + CASE WHEN LEN(IDNumber) < 10 THEN '0' ELSE '' END + 
             + CAST(LEN(IDNumber) AS varchar)
             + IDNumber
FROM #TEMP_TABLE_ID