开发者

MAX on Char-Columns in SQL-Server

i have a char(10) column in a table in a SQL-Server 2005 database:

CREATE TABLE [dbo].[RMA](
    [IdRMA] [int] IDENTITY(1,1) NOT NULL,
    [RMA_Number] [char](10) NULL
 CONSTRAINT [PK_RMA] PRIMARY KEY CLUSTERED 
(
    [IdRMA] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[RMA]  WITH CHECK ADD  CONSTRAINT [CK_UNIQUE_RMA_NUMBER] CHECK  (([rma_number] IS NULL OR [dbo].[_CountRmaNumber]([rma_number])<(2)))
GO
ALTER TABLE [dbo].[RMA] CHECK CONSTRAINT [CK_UNIQUE_RMA_NUMBER]

I know that it would be better to make it an Int-Column, when i want to order by or aggregate it. But what i want to know is, is it nevertheless guaranteed 开发者_高级运维that a SELECT MAX(RMA_Number) always returns the highest number in SQL-Server? The format of the values f.e. is: RMA0003715. RMA_Number is a consecutive number with 10 chars that always start with RMA.

EDIT: Thanks to all for the confirmation and for James Wiseman for the advice to check for the correct format. I added a constraint:

ALTER TABLE [dbo].[RMA]  WITH CHECK ADD  CONSTRAINT [CK_UNIQUE_RMA_NUMBER] CHECK  (([rma_number] IS NULL OR [dbo].[_CountRmaNumber]([rma_number])<(2)))
ALTER TABLE [dbo].[RMA] CHECK CONSTRAINT [CK_RMA_Number_Format]

Thank you.


If the field is always of the format RMAxxxxxxx (RMA followed by 7 numbers), then yes, MAX will always return the highest one.

I believe all of the available collations work exactly the same on the numeric portion of the field.


MAX(RMA_Number) will sort numeric fields numerically and text/char/varchar fields alphabetically.

If your data is of a guaranteed format, and then numeric part will always be left-padded with zeros then, your MAX function will work.

However, you don't appear to have anything in place to maintain this data requriement. Although you are assuming it will alway be of the format, there is nothing in practice to prevent an erroneous value being inserted. I suggest you enhance your check constrants on teh field to catch this.


As far as collations do not affect sorting by provided column the answer is yes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜