相比之下,说:
REPLICATE(@padchar, @len - LEN(@str)) + @str
相比之下,说:
REPLICATE(@padchar, @len - LEN(@str)) + @str
当前回答
要提供四舍五入到小数点后两位,但如果需要,右补零,我有:
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格式发送电子邮件报告,因此希望格式化信息,而不涉及额外的工具来解析数据。
其他回答
我知道这个问题最初是在2008年提出的,但是在SQL Server 2012中引入了一些新函数。FORMAT函数很好地简化了以零结尾的填充。它也会为你执行转换:
declare @n as int = 2
select FORMAT(@n, 'd10') as padWithZeros
更新:
我想亲自测试FORMAT函数的实际效率。我很惊讶地发现,与AlexCuse的原始答案相比,效率不是很好。虽然我发现FORMAT函数更简洁,但就执行时间而言,它不是很高效。我使用的tallytable有64,000条记录。Martin Smith指出了执行时间效率。
SET STATISTICS TIME ON
select FORMAT(N, 'd10') as padWithZeros from Tally
SET STATISTICS TIME OFF
SQL Server执行次数: CPU时间= 2157 ms,运行时间= 2696 ms。
SET STATISTICS TIME ON
select right('0000000000'+ rtrim(cast(N as varchar(5))), 10) from Tally
SET STATISTICS TIME OFF
SQL Server执行次数:
CPU时间= 31 ms,运行时间= 235 ms。
我用这个。它允许您确定想要的结果长度,以及如果没有提供默认填充字符。当然,您可以为遇到的任何最大值定制输入和输出的长度。
/*===============================================================
Author : Joey Morgan
Create date : November 1, 2012
Description : Pads the string @MyStr with the character in
: @PadChar so all results have the same length
================================================================*/
CREATE FUNCTION [dbo].[svfn_AMS_PAD_STRING]
(
@MyStr VARCHAR(25),
@LENGTH INT,
@PadChar CHAR(1) = NULL
)
RETURNS VARCHAR(25)
AS
BEGIN
SET @PadChar = ISNULL(@PadChar, '0');
DECLARE @Result VARCHAR(25);
SELECT
@Result = RIGHT(SUBSTRING(REPLICATE('0', @LENGTH), 1,
(@LENGTH + 1) - LEN(RTRIM(@MyStr)))
+ RTRIM(@MyStr), @LENGTH)
RETURN @Result
END
你的里程可能会有所不同。: -) 乔伊摩根 一级程序设计/分析主任 WellPoint医疗补助事业单位
要提供四舍五入到小数点后两位,但如果需要,右补零,我有:
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格式发送电子邮件报告,因此希望格式化信息,而不涉及额外的工具来解析数据。
下面是我的解决方案,它避免了截断字符串并使用普通的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;
这是我的解决方案。我可以填充任何字符,它是快速的。选择简单。您可以更改可变大小以满足您的需要。
更新了一个参数来处理如果为空返回什么:null如果为空将返回null
CREATE OR ALTER FUNCTION code.fnConvert_PadLeft(
@in_str nvarchar(1024),
@pad_length int,
@pad_char nchar(1) = ' ',
@rtn_null NVARCHAR(1024) = '')
RETURNS NVARCHAR(1024)
AS
BEGIN
DECLARE @rtn NCHAR(1024) = ' '
RETURN RIGHT(REPLACE(@rtn,' ',@pad_char)+ISNULL(@in_str,@rtn_null), @pad_length)
END
GO
CREATE OR ALTER FUNCTION code.fnConvert_PadRight(
@in_str nvarchar(1024),
@pad_length int,
@pad_char nchar(1) = ' ',
@rtn_null NVARCHAR(1024) = '')
RETURNS NVARCHAR(1024)
AS
BEGIN
DECLARE @rtn NCHAR(1024) = ' '
RETURN LEFT(ISNULL(@in_str,@rtn_null)+REPLACE(@rtn,' ',@pad_char), @pad_length)
END
GO
-- Example
SET STATISTICS time ON
SELECT code.fnConvert_PadLeft('88',10,'0',''),
code.fnConvert_PadLeft(null,10,'0',''),
code.fnConvert_PadLeft(null,10,'0',null),
code.fnConvert_PadRight('88',10,'0',''),
code.fnConvert_PadRight(null,10,'0',''),
code.fnConvert_PadRight(null,10,'0',NULL)
0000000088 0000000000 NULL 8800000000 0000000000 NULL