How can I set up a simple calculated field in SQL Server?

好久不见. 提交于 2019-12-20 17:59:49

问题


I have a table with several account fields like this:

MAIN_ACCT
GROUP_ACCT
SUB_ACCT

I often need to combine them like this:

SELECT MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT
FROM ACCOUNT_TABLE

I'd like a calculated field that automatically does this, so I can just say:

SELECT ACCT_NUMBER FROM ACCOUNT_TABLE

What is the best way to do this?

I'm using SQL Server 2005.


回答1:


ALTER TABLE ACCOUNT_TABLE 
ADD ACCT_NUMBER AS MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT PERSISTED

This will persist a calculated column and may perform better in selects than a calculation in view or UDF if you have a large number of records (once the intial creation of the column has happened which can be painfully slow and should probably happen during low usage times). It will slow down inserts and updates. Usually I find a slow insert or update is tolerated better by users than a delay in a select unless you get locking issues.

The best method for doing this will depend a great deal on your usage and what kind of performance you need. If you don't have a lot of records or if the computed column won't be called that frequently, you may not want a persisted column, but if you are frequently running reports with all the records for the year or other large sets of data, you may find the persisted calculated column works better for you. As with any task of this nature, the only way to know what works best in your situation is to test.




回答2:


This is a great candidate for a View.

CREATE VIEW vwACCOUNT_TABLE
AS

SELECT MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT AS ACCT_NUMBER 
FROM ACCOUNT_TABLE

GO

--now select from the View
SELECT ACCT_NUMBER FROM  vwACCOUNT_TABLE



回答3:


ALTER TABLE ACCOUNT_TABLE ADD ACCT_NUMBER AS MAIN_ACCT+'-'+GROUP_ACCT+'-'+SUB_ACCT;

the column is not persisted in the table, will be recreated on-the-cly each time you reference it. You can achieve the same result by using a view. If you use filtering predicates or ordering on the computed column and want to add an index on it see Creating Indexes on Computed Columns.




回答4:


Well, you could create a view of the ACCOUNT_TABLE and query that. Or I believe you could create a user defined function which would accomplish the same thing.



来源:https://stackoverflow.com/questions/1274582/how-can-i-set-up-a-simple-calculated-field-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!