Tsql 在sql server 2008r的CAST coalesce row_number()over语句中,预置前导零的最佳方法是什么

Tsql 在sql server 2008r的CAST coalesce row_number()over语句中,预置前导零的最佳方法是什么,tsql,Tsql,我已经正确地添加了第三列,但还需要为第二列上的9个字符添加0。我有一个查询的示例,它部分有效。我看到了几种预装的方法 它需要格式 000001234 000123456 SELECT 'P', --coalesce-return the first nonnull expression, row_number-numbers all rows sequentially, over-defines a window *[need to prepad here]* CAST(coalesce(xy

我已经正确地添加了第三列,但还需要为第二列上的9个字符添加0。我有一个查询的示例,它部分有效。我看到了几种预装的方法

它需要格式

000001234 000123456

SELECT 'P', 
--coalesce-return the first nonnull expression, row_number-numbers all rows sequentially, over-defines a window
*[need to prepad here]* CAST(coalesce(xyz.MaxID, 0) as int) + row_number() over (order by(select NULL)) as theMax,
'P' + right('000000000'+ rtrim(CAST((CAST(coalesce(xyz.MaxID, 0) as int) + row_number() over (order by(select NULL))) as VARCHAR(50))), 9), 
T.ForeName, T.Middle_Name, T.Surname, '1234', 'n', GetDate(), GetDate(), 'SCT', '1', GetDate(), GetDate(), 'PGHERE', '1', 'n'
FROM INSERTED  i 
cross join 
--selecting max number between people or changes
(SELECT MAX(CAST(q1.Test as INT)) as MaxID FROM (SELECT MAX(CAST(PEOPLE_ID as INT)) as Test FROM pc.dbo.People WHERE CAST(PEOPLE_ID as int)<2000000 UNION ALL SELECT MAX(CAST(PEOPLE_ID as INT)) as Test FROM pc.dbo.Changes WHERE CAST(PEOPLE_ID as int)<2000000) q1) AS xyz
--used for testing since inserted table only exists in the context of the trigger when it's executing
CROSS APPLY dbo.Parser(i.Contact) T
WHERE i.Key1 = '23'
OR (i.Key1 = '45')
OR (i.Key1 = '67')
使用replicatestring表达式、整数表达式


这将导致一个包含9个字符的字段,在9的总长度中有多少个字符丢失之前有0

我不确定,我没有投反对票,但我相信对于如何制定一个问题以最好地给你你想要的答案,有一个标准的期望。例如,显示您正在查找的输出、设置有助于运行您发布的查询的模式的基本查询等。。这可能就是原因。这是这个论坛上唯一一个关于prepad前导零的问题,包括CAST,coalesce,row_number,over语句。为什么要被否决?
replicate('0', 9 - len(YourFieldName))