3

可能重复:
在 sql server 中修剪左边的字符?

我在下面有一个查询,它从我们的数据库中获取客户信息以发送优惠券。关于邮政编码,我们只需要该字段的前 5 位数字......我怎样才能只返回前 5 位?我的代码如下:

SELECT        Invoice_Tb.Customer_First_Name AS firstname, Invoice_Tb.Customer_Last_Name AS lastname, Invoice_Tb.Customer_Address AS add1, Invoice_Tb.City, 
                         Invoice_Tb.Customer_State AS State, Invoice_Tb.ZIP_Code AS ZIP, Invoice_Tb.Customer_Email_Address AS [Email Address], 
                         Invoice_Tb.Vehicle_Mileage AS [Vehicle Mileage], Invoice_Tb.Invoice_Date AS [Date Of Service], Invoice_Tb.Store_Number, @startdate AS Start_Date, @enddate AS End_Date
FROM            Invoice_Detail_Tb INNER JOIN
                         Invoice_Tb ON Invoice_Detail_Tb.Invoice_Number = Invoice_Tb.Invoice_Number AND Invoice_Detail_Tb.Invoice_Date = Invoice_Tb.Invoice_Date
WHERE        (Invoice_Detail_Tb.Store_Category_Code = 'FS') AND (Invoice_Tb.Invoice_Date BETWEEN CONVERT(DATETIME, @startdate, 102) AND CONVERT(Datetime, 
                         @enddate, 102)) AND (Invoice_Tb.Reminder_Mail_Flag = 'Y')
4

2 回答 2

6

尝试

LEFT(FieldName, 5)

例如

SELECT LEFT(FieldName, 5) as SomeAlias FROM SomeTable

桌子:

FieldName
---------
Hello World

结果:

SomeAlias
---------
Hello
于 2012-09-01T12:45:55.933 回答
0

如果您的字段是 Invoice_Tb.ZIP_Code,您可以使用 substring 函数:

substring(Invoice_Tb.ZIP_Code, 1, 5) AS 'Trimmed Zip Code'

另一种选择是使用 LEFT 功能:

LEFT(Invoice_Tb.ZIP_Code, 5) AS 'Trimmed Zip Code'

由于存在从整数到 nvarchar 和 nvarchar 等价物的隐式转换,因此无需担心在这里进行 CAST。

于 2012-09-01T12:54:13.410 回答