实际上,我上周才这样做。我编写了一个函数,然后为我调用该函数的每个字段执行此操作。
这是功能
/*
USE [Newton-Dev]
GO
/****** Object: UserDefinedFunction [dbo].[CharPad] Script Date: 1/10/2015 11:38:27 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Script : Character Padding Function; Assist with fixed width file creation
Version : 1.0 (01/08/2015)
Author : Jeffery Williams
*/
ALTER FUNCTION [dbo].[CharPad] (
@Input VARCHAR(255)
,@OutputWidth INT
,@OutputAlign VARCHAR(5)
,@PadCharacter CHAR(1) )
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @Output VARCHAR(255)
DECLARE @InputWidth INT
SET @InputWidth = LEN(@Input)
IF @InputWidth > @OutputWidth
BEGIN
IF @OutputAlign = 'LEFT'
BEGIN
SET @Output = LEFT(@Input,@OutputWidth)
END
IF @OutputAlign = 'RIGHT'
BEGIN
SET @Output = RIGHT(@Input,@OutputWidth)
END
END
IF @InputWidth < @OutputWidth
BEGIN
IF @OutputAlign = 'RIGHT'
BEGIN
SET @Output = REPLICATE(@PadCharacter, @OutputWidth - @InputWidth ) + @Input
END
IF @OutputAlign = 'LEFT'
BEGIN
SET @Output =@Input+ REPLICATE(@PadCharacter, @OutputWidth - @InputWidth )
END
END
IF @InputWidth = @OutputWidth
SET @Output = @Input
RETURN (@Output)
END
这是调用该函数并提供固定宽度输出的查询:
SELECT --dbo.CharPad (DeltaLineId,8,'LEFT',' '), dbo.CharPad (DeltaElgId,8,'LEFT',' ')
dbo.CharPad (CARRIER_ID,6,'LEFT',' ')
,dbo.CharPad (GROUP_NUM,7,'RIGHT','0')
,dbo.CharPad (LEFT('0000' + SUB_GROUP_ID, 4),9,'LEFT',' ')
,dbo.CharPad (SVC_TYPE,1,'LEFT',' ')
,dbo.CharPad (FILLER_1,1,'LEFT',' ')
,dbo.CharPad (FILLER_2,5,'LEFT',' ')
,dbo.CharPad (RATE_CODE,2,'LEFT',' ')
,dbo.CharPad (FILLER_3,1,'LEFT',' ')
,dbo.CharPad (ELIG_CODE,1,'LEFT',' ')
,dbo.CharPad (EFF_DATE,8,'LEFT',' ')
,dbo.CharPad (TERM_DATE,8,'LEFT',' ')
,dbo.CharPad (SUBSC_SSN,9,'LEFT',' ')
,dbo.CharPad (INDIV_SSN,9,'LEFT',' ')
,dbo.CharPad (CHNG_SSN,9,'LEFT',' ')
,dbo.CharPad (REL_CODE,2,'LEFT',' ')
,dbo.CharPad (HIRE_DATE,8,'LEFT',' ')
,dbo.CharPad (DOB,8,'LEFT',' ')
,dbo.CharPad (REL_TYPE,1,'LEFT',' ')
,dbo.CharPad (FIRST_NAME,24,'LEFT',' ')
,dbo.CharPad (MID_NAME,24,'LEFT',' ')
,dbo.CharPad (LAST_NAME,24,'LEFT',' ')
,dbo.CharPad (GENDER,1,'LEFT',' ')
,dbo.CharPad (POP_DESC,5,'LEFT',' ')
,dbo.CharPad (ADR_LINE_1,30,'LEFT',' ')
,dbo.CharPad (ADR_LINE_2,30,'LEFT',' ')
,dbo.CharPad (CITY,30,'LEFT',' ')
,dbo.CharPad ([STATE],2,'LEFT',' ')
,dbo.CharPad (COUNTY_CODE,3,'LEFT',' ')
,dbo.CharPad (COUNTRY_CODE,3,'LEFT',' ')
,dbo.CharPad (ZIP,5,'LEFT',' ')
,dbo.CharPad (ZIP_EXT,4,'LEFT',' ')
,dbo.CharPad (FILLER_4,21,'LEFT',' ')
,dbo.CharPad (USER_DEFINED,30,'LEFT',' ')
,dbo.CharPad (WAIT_PERIOD,1,'LEFT',' ')
,dbo.CharPad (CAID,9,'RIGHT','0')
,dbo.CharPad (FILLER_5,9,'LEFT',' ')
FROM export.DeltaLine
*/