【转】sqlserver中的Lpad 和 Rpad

From :

http://www.developerdotstar.com/community/node/319

Code :


/**************** LPad ***********************/


IF EXISTS (

SELECT *

FROM dbo.sysobjects

WHERE id = object_id(N'[dbo].[LPad]')

AND xtype IN (N'FN', N'IF', N'TF')

)

DROP FUNCTION [dbo].[LPad]

GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_NULLS ON

GO

CREATE FUNCTION LPad( @PadChar char(1), @PadToLen int, @BaseString varchar(100))

RETURNS varchar(1000)

AS

/* ****************************************************

Author: Daniel Read

Description: Pads @BaseString to an exact length (@PadToLen)

using the specified character (@PadChar). Base string will not be

trimmed. Implicit type conversion should allow caller to

pass a numeric T-SQL value for @BaseString.

Unfortunately T-SQL string variables must be declared with an

explicit width, so I chose 100 for the base and 1000 for the

return. Feel free to adjust data types to suit your needs.

Keep in mind that if you don't assign an explicit width to

varchar it is the same as declaring varchar(1).

Revision History: Date

Name Description ---- ---- -----------

***************************************************** */

BEGIN

DECLARE @Padded varchar(1000)

DECLARE @BaseLen int

SET @BaseLen = LEN(@BaseString)

IF @BaseLen >= @PadToLen

BEGIN

SET @Padded = @BaseString

END ELSE BEGIN

SET @Padded = REPLICATE(@PadChar, @PadToLen - @BaseLen) + @BaseString

END

RETURN @Padded

END

GO

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO

例子:

SELECT dbo.LPad('0', 3, '1')

001

/**************** RPad ***********************/

IF EXISTS (
SELECT *
FROM dbo.sysobjects
WHERE id = object_id(N'[dbo].[RPad]')
AND xtype IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[RPad]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE FUNCTION RPad(
@PadChar char(1),
@PadToLen int,
@BaseString varchar(100))
RETURNS varchar(1000)
AS
/* ****************************************************
Author: Daniel Read
Description: Pads @BaseString to an exact length (@PadToLen) using the
specified character (@PadChar). Base string will not be
trimmed. Implicit type conversion should allow caller to
pass a numeric T-SQL value for @BaseString.
Unfortunately T-SQL string variables must be declared with an
explicit width, so I chose 100 for the base and 1000 for the
return. Feel free to adjust data types to suit your needs.
Keep in mind that if you don't assign an explicit width to
varchar it is the same as declaring varchar(1).
Revision History: Date
Name Description ---- ---- -----------
**************************************************** */
BEGIN
DECLARE @Padded varchar(1000)
DECLARE @BaseLen int
SET @BaseLen = LEN(@BaseString)
IF @BaseLen >= @PadToLen
BEGIN
SET @Padded = @BaseString
END ELSE BEGIN
SET @Padded = @BaseString + REPLICATE(@PadChar, @PadToLen - @BaseLen)
END
RETURN @Padded
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

例子:

select dbo.Rpad('0',3,'1')

100

你可能感兴趣的:(Go,SQL)