相比之下,说:
REPLICATE(@padchar, @len - LEN(@str)) + @str
相比之下,说:
REPLICATE(@padchar, @len - LEN(@str)) + @str
当前回答
这个怎么样:
replace((space(3 - len(MyField))
3是要填充的零的个数
其他回答
下面是我的解决方案,它避免了截断字符串并使用普通的SQL。感谢@AlexCuse, @Kevin和@Sklivvz,他们的解决方案是这段代码的基础。
--[@charToPadStringWith] is the character you want to pad the string with.
declare @charToPadStringWith char(1) = 'X';
-- Generate a table of values to test with.
declare @stringValues table (RowId int IDENTITY(1,1) NOT NULL PRIMARY KEY, StringValue varchar(max) NULL);
insert into @stringValues (StringValue) values (null), (''), ('_'), ('A'), ('ABCDE'), ('1234567890');
-- Generate a table to store testing results in.
declare @testingResults table (RowId int IDENTITY(1,1) NOT NULL PRIMARY KEY, StringValue varchar(max) NULL, PaddedStringValue varchar(max) NULL);
-- Get the length of the longest string, then pad all strings based on that length.
declare @maxLengthOfPaddedString int = (select MAX(LEN(StringValue)) from @stringValues);
declare @longestStringValue varchar(max) = (select top(1) StringValue from @stringValues where LEN(StringValue) = @maxLengthOfPaddedString);
select [@longestStringValue]=@longestStringValue, [@maxLengthOfPaddedString]=@maxLengthOfPaddedString;
-- Loop through each of the test string values, apply padding to it, and store the results in [@testingResults].
while (1=1)
begin
declare
@stringValueRowId int,
@stringValue varchar(max);
-- Get the next row in the [@stringLengths] table.
select top(1) @stringValueRowId = RowId, @stringValue = StringValue
from @stringValues
where RowId > isnull(@stringValueRowId, 0)
order by RowId;
if (@@ROWCOUNT = 0)
break;
-- Here is where the padding magic happens.
declare @paddedStringValue varchar(max) = RIGHT(REPLICATE(@charToPadStringWith, @maxLengthOfPaddedString) + @stringValue, @maxLengthOfPaddedString);
-- Added to the list of results.
insert into @testingResults (StringValue, PaddedStringValue) values (@stringValue, @paddedStringValue);
end
-- Get all of the testing results.
select * from @testingResults;
要提供四舍五入到小数点后两位,但如果需要,右补零,我有:
DECLARE @value = 20.1
SET @value = ROUND(@value,2) * 100
PRINT LEFT(CAST(@value AS VARCHAR(20)), LEN(@value)-2) + '.' + RIGHT(CAST(@value AS VARCHAR(20)),2)
如果有人能想出一种更简洁的方法,那将是非常感激的——上面的方法似乎很笨拙。
注意:在本例中,我使用SQL Server以HTML格式发送电子邮件报告,因此希望格式化信息,而不涉及额外的工具来解析数据。
这是一个简单的左填充方法:
REPLACE(STR(FACT_HEAD.FACT_NO, x, 0), ' ', y)
其中x是填充号y是填充字符。
示例:
REPLACE(STR(FACT_HEAD.FACT_NO, 3, 0), ' ', 0)
这是我通常如何填充一个varchar
WHILE Len(@String) < 8
BEGIN
SELECT @String = '0' + @String
END
我不确定你给出的方法真的是低效的,但另一种方法,只要它不需要灵活的长度或填充字符,将是(假设你想用“0”到10个字符填充它:
DECLARE
@pad_characters VARCHAR(10)
SET @pad_characters = '0000000000'
SELECT RIGHT(@pad_characters + @str, 10)