TSQL计算列限制

时间:2010-10-07 02:56:22

标签: sql sql-server tsql sql-server-2008 calculated-columns

CREATE TABLE [dbo].[MembershipModule](
 [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 [ParentId] [uniqueidentifier] NULL,
 [TargetId] [int] NULL,
 [WebContentId] [uniqueidentifier] NULL,
 [Name] [varchar](35) NOT NULL,
 [NameUpper]  AS (isnull(upper([Name]),'')) PERSISTED NOT NULL,
 [UriPrefix] [varchar](max) NULL,
 [UriText] [varchar](max) NULL,
 [UriComputed]  AS ??? PERSISTED,
 [Description] [varchar](100) NULL,
 [Created] [date] NOT NULL,
 [Modified] [datetime2](7) NOT NULL,
 [MenuItem] [bit] NOT NULL,
 [Enabled] [bit] NOT NULL,
 [Position] [smallint] NULL,
 CONSTRAINT [PK_MembershipModule] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

到目前为止,UriComputed字段的计算如下:

lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))

这会产生如下输出

Results

现在,我想用'/'终止所有UriComputed值。通过向计算字段添加+ '/'可以很容易地实现这一点,除了“无文字”uris将像//一样终止这一事实,我不想发生这种情况。

因为我可以放入计算字段的sql非常有限(而且我真的不知道这些限制的范围)我想我会问这里如何添加它。

基本上我希望图像中的输出为

/a/login/
/a/announcements/
/a/
/

我最近的尝试是:

isnull(convert(varchar(MAX),nullif(len(coalesce([UriText],[Name])),0)),'/')

哪种情况有点混乱,如果它应以'/'结尾,则添加一个数字,并在应该添加'/'时,我需要的是相反的(即长度为'/')是0,'否则)

如果有一个内联的if或类似的东西我可以使用它基本上是它,但我不知道。

谢谢!

1 个答案:

答案 0 :(得分:5)

这对我有用:

[UriComputed]  AS (CASE 
                     WHEN RIGHT(lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')), 1) = '/' THEN
                       lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))
                     ELSE
                       lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')) +'/'
                   END) PERSISTED,

完整的CREATE TABLE语句:

CREATE TABLE [dbo].[MembershipModule](
 [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 [ParentId] [uniqueidentifier] NULL,
 [TargetId] [int] NULL,
 [WebContentId] [uniqueidentifier] NULL,
 [Name] [varchar](35) NOT NULL,
 [NameUpper]  AS (isnull(upper([Name]),'')) PERSISTED NOT NULL,
 [UriPrefix] [varchar](max) NULL,
 [UriText] [varchar](max) NULL,
 [UriComputed]  AS (CASE 
                     WHEN RIGHT(lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')), 1) = '/' THEN
                       lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))
                     ELSE
                       lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')) +'/'
                    END) PERSISTED,
 [Description] [varchar](100) NULL,
 [Created] [date] NOT NULL,
 [Modified] [datetime2](7) NOT NULL,
 [MenuItem] [bit] NOT NULL,
 [Enabled] [bit] NOT NULL,
 [Position] [smallint] NULL)