开发者

SQL Server: Computed Expression error

开发者 https://www.devze.com 2023-01-21 14:59 出处:网络
Here\'开发者_如何学Pythons a table with a computed column in SQL Server 2005: CREATE TABLE footable AS

Here'开发者_如何学Pythons a table with a computed column in SQL Server 2005:

CREATE TABLE footable AS
  [identifier] nvarchar(255) NOT NULL,
  [result]     AS CASE 
    WHEN [identifier] like '%\[%]' escape '\'
    THEN LEFT( [identifier], CHARINDEX('[',[identifier]) - 1 )
    END

Here's what I'm expecting:

identifier      result
======================
foo[bar]        foo
foo             NULL

This worked a few days ago, and has been working for over a year.

Then yesterday, I started getting this error when inserting or updating with identifier values that had no [, when a NULL would be the expected result:

Invalid length parameter passed to the left function.

Now, today, it's working again.

Why would SQL Server be attempting to solve the LEFT() function when the CASE is not true?

More importantly, why is it working one day and not the next?

I was also creating some indexed views yesterday, though not covering either of these columns. Could one of the SET options required for indexing a view cause the database to start throwing errors for an expression like this?


I would use

N'[^[]%\[%]' escape N'\'  

That should handle the possibility that the first character is a [.

Or, if you want to return a non-null (empty string?) in that case, use a nested CASE to handle the condition of CHARINDEX returning 1.

By the way, you don't really need that escape character or escape clause. You can use [[] to match the [ character:

N'[^[]%[[]%]'

But, that's a matter of personal taste. I can see how the escaped version is a little clearer

0

精彩评论

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