Best practice to avoid code replication?
-
23-03-2021 - |
Question
currently I have to change a view, a big part of the view code looks like this:
CAST('My_Tag_' + CASE
WHEN FieldX isnull
THEN ''
WHEN FieldX = '123'
THEN 'some_number'
WHEN FieldX = 'abc'
THEN 'some_text'
ELSE 'strange' ) AS VARCHAR(128) AS myField
)
Just a chunk of code, that puts together a string (the code itself doesn't even matter right now, I have like 50 other examples, where I have a lot of code replication). Now I have exact the same code for 30 more fields in the view, just the 'My_Tag_' and FieldX is changing. If this would be C#, I would just write a little helper function. Of course I could write a function here, too. But as this is a bigger project with a lot of tables, views, etc, I would have hundreds of functions soon.
Now I am pretty new to SQL and normally my home is the OOP-world. But there has to be a solution to avoid code replication and to avoid having hundreds of helper functions in the database?
What's best practice in this case?
Solution
The best practice may be to create a user defined function.
The arguments would be the fields that change and it would return the intended value.
OTHER TIPS
You can use a CTE to add a field to a table:
; with TableWithExtraField as
(
select case ... end as NewField
, table1
)
select NewField
from TableWithExtraField
Or a subquery also works:
select NewField
from (
select case ... end as NewField
, table1
) as TableWithExtraField
CREATE FUNCTION dbo.MyTag(@myfield VARCHAR(MAX))
RETURNS VARCHAR(128)
AS
BEGIN
RETURN CAST('My_Tag_' + CASE
WHEN @myfield IS NULL
THEN ''
WHEN @myfield = '123'
THEN 'some_number'
WHEN @myfield = 'abc'
THEN 'some_text'
ELSE 'strange' END AS VARCHAR(128))
)
END