Use scalar function in sql to realize the simple writing method of case when

First create a scalar function that contains case when

insert image description here
Attached code:
CREATE FUNCTION [dbo].Fn_GetSignModeCode
(
@Name VARCHAR(100)
)
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE @Return VARCHAR(20)

SET @Return =CASE @Name
when'Strategic Procurement'then'01'
when'Strategic Cooperation'then'02' when'Strategic
Agreement'then'03'
END
RETURN @Return
end
GO
How to use:
select dbo.Fn_GetSignModeCode('Strategy purchase')
to get the value: 01
insert image description here
How to use this scalar function in the sql script:
SELECT
dbo.Fn_GetSignModeCode(x_SignMode) AS purchase method
FROM table name

When not using the created scalar function:
insert image description here
the logic of the scalar function feels like writing a public method in the project.
When there are many places to use, write a scalar function for easy use. The code will be cleaner

Guess you like

Origin blog.csdn.net/qq_37213281/article/details/109819695