USER_NAME, FS_USER and FS_USERNAME in v15

I'm going through Custom data objects flagged by the Migration - Customization Review report, and one of the items is instances of the user of "USER_NAME".  I'd mostly cleared those away, I expect the remainder will be innocuous or deprecated procs and tables.  However, I've learned that FS_USER is now actually deprecated in favor of FS_USERNAME, so I thought I'd throw that warning out there.

But I was also dissatisfied with FS_USER (and its successor) as it truncates names longer than 8 characters to the first 8 characters.  FS_USERNAME tries to be clever and truncate to the first 8 characters after the domain name, but our org prefix on RAMP (and I expect many) is actually 8 characters, so the all important number is lost.  Moreover, with Windows Authentication, there is now the possibility of matching an AD name to an account in T_METUSER.

I also hadn't been using fs_get_param_from_appname, apparently the preferred way of deducing the userid when in things like the client.

I also like to be able to override any deduced name so that for utilities, like those in SQL Server Agent Jobs, can potentially declare themselves as something other than "dbo", and I can potentially recognize which script is being used (although the main use, in constraints, doesn't really support that).

In case anyone is interested, here is my "LF_CPSMA_USER_NAME function:


use impresario
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

/*
	Updated 2019/07/03
	Learned from Tessitura's built-in functions, but also improving.
	1) Using RIGHT, so that we get the all-important number in the AD name
	2) trying to match the AD name to T_METUSER if possible
	3) new heirarchy:
		passed in name (for scripts, utilities and sql server agent jobs)
		context defined name (typically client, uses fs_get_param_from_appname)
		ad name attached to T_METUSER account (mostly me working in SSMS)
		SUSER_NAME (instead of USER_NAME, not sure difference)
		default 'Unknown' if all else fails
*/

IF OBJECT_ID('[dbo].[LF_CPSMA_USER_NAME]', 'FN') IS NOT NULL
	DROP FUNCTION [dbo].[LF_CPSMA_USER_NAME]
GO
CREATE FUNCTION [dbo].[LF_CPSMA_USER_NAME] (
	@alt_user_name varchar(8)
)
RETURNS varchar(8)
AS
BEGIN
	RETURN
		RIGHT(
			COALESCE(
				@alt_user_name,
				dbo.fs_get_param_from_appname('uid'),
				(select TOP(1) mu.userid from T_METUSER as mu where mu.active_directory_username = SUSER_NAME()),
				SUSER_NAME(),
				'Unknown'
			),
		8)
END


GO
GRANT EXECUTE ON [dbo].[LF_CPSMA_USER_NAME] TO [ImpUsers]
GO