从sql server输出到csv时阻止前导零被剥离

时间:2013-07-05 15:30:27

标签: sql

您好我有一个SQL脚本,它将一些数据列(其中一个是电话号码)输出到csv文件中。该脚本一切正常但是从电话号码中删除了前导零。现在我知道为什么在包含它们的excel中打开csv时,从电话号码中删除前导零的原因。

我挣扎的是用双引号括起电话号码的SQL脚本,以便在打开时将其解释为文本。看下面我的sql:

SET @query ='
SELECT
    ''MobilePhoneNumber'' AS MobilePhoneNumber
    ,''RequestNumber'' AS RequestNumber
    ,''RequestDate'' AS RequestDate
    ,''RequestType'' AS RequestType
    ,''Status'' AS Status
UNION ALL
SELECT 
    [MobilePhoneNumber] --I Want to get this column in the csv as EG "01234123456"
    ,[RequestNumber]
    ,CONVERT(VARCHAR,[RequestDate],120)
    ,[RequestType]
    ,[Status]
FROM [Mobiles].[dbo].[Requests]
WHERE [RequestType] = ''Cease''
    AND DATEDIFF(mm,Requestdate , GETDATE())=1;'

2 个答案:

答案 0 :(得分:1)

试试这个:

'...
SELECT 
CHAR(34) + [MobilePhoneNumber] + CHAR(34)
...'

'...
SELECT 
''"'' + [MobilePhoneNumber] + ''"''
...'

答案 1 :(得分:0)

感谢@KekuSemau的建议这是我的解决方案,最终为了他人的利益:

SET @query ='
SELECT
    ''MobilePhoneNumber'' AS MobilePhoneNumber
    ,''RequestNumber'' AS RequestNumber
    ,''RequestDate'' AS RequestDate
    ,''RequestType'' AS RequestType
    ,''Status'' AS Status
UNION ALL
SELECT 
    CHAR(39) +[MobilePhoneNumber] -- < I simply added the CHAR(39)
    ,[RequestNumber]
    ,CONVERT(VARCHAR,[RequestDate],120)
    ,[RequestType]
    ,[Status]
FROM [Mobiles].[dbo].[Requests]
WHERE [RequestType] = ''Cease''
    AND DATEDIFF(mm,Requestdate , GETDATE())=1;'