SQL SERVER 字段统一补0方法
Posted One is never too old to learn.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL SERVER 字段统一补0方法相关的知识,希望对你有一定的参考价值。
在SQL SERVER 2008R2的[AdventureWorks2008R2]示例数据库中,看到以下字段统一补0方法。
将CustomerID前面加0转变为AccountNumber字段。
CREATE TABLE [Sales].[Customer](
[CustomerID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[PersonID] [int] NULL,
[StoreID] [int] NULL,
[TerritoryID] [int] NULL,
[AccountNumber] AS (isnull(‘AW‘+[dbo].[ufnLeadingZeros]([CustomerID]),‘‘)),
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
CONSTRAINT [PK_Customer_CustomerID] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
=====
Scalar function used by the Sales.Customer table to help set the account number.
---
CREATE FUNCTION [dbo].[ufnLeadingZeros](
@Value int
)
RETURNS varchar(8)
WITH SCHEMABINDING
AS
BEGIN
DECLARE @ReturnValue varchar(8);
SET @ReturnValue = CONVERT(varchar(8), @Value);
SET @ReturnValue = REPLICATE(‘0‘, 8 - DATALENGTH(@ReturnValue)) + @ReturnValue;
RETURN (@ReturnValue);
END;
以上是关于SQL SERVER 字段统一补0方法的主要内容,如果未能解决你的问题,请参考以下文章
如何在 sql server 中定位自由文本字段中的 16 位数字字符串?