sql - Create a complex index on SQL Server
问题描述
Is it possible to somehow create an index on an expression so I can, for example, write a query against a field that is string, but meant to be numeric?
For example, I inherited a database that has a column PolarFactor
which stores values like "234.28234" and is of type varchar(100)
.
I want to efficiently query that column, getting all rows with values in between 200 and 300.
Would be great if you could do something like this....
create index i1 on table(CAST(PolarFactor as Double))
This is not valid.
But I am wondering if either there is a way to do it, or if somebody has a better idea.
解决方案
Yes. Use a computed column:
alter table t add polarfactor_double as (try_cast(PolarFactor as double)) persisted;
create index i1 on t(PolarFactor_Double);
Note that I use try_cast()
instead of cast()
, so errors don't cause inserts to break.
Also, you should probably fix your data so PolarFactor
is stored using the correct data type. Don't store numbers as strings.
推荐阅读
- r - 如何使用条形图微调 Plotly 的 dragmode = 'select'
- amazon-web-services - 试图从 sqs 触发我的 lambda 函数,它正在触发 lambda 但队列中没有消息
- amazon-cloudformation - 带有letsencrypt SSL证书的AWS Cloudformation模板
- sql-server - 如何在 SQL Server 的合并复制中将现有触发器更改为“不用于复制”?
- php - 对 setParameter() 方法使用 $hash
- php - PHP DOMElement appendChild get DOMException Wrong Document Error
- react-native - 实时响应本机更改输入值
- docker - 即使我满足它们,Docker 构建也会因依赖问题而失败
- shiny - 闪亮:renderText 因条件滑动条而失败
- javascript - 这个声明是如何工作的: var x = new X(), Y;