Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
-- In the year 2020, we have self-driving cars, but MSSQL doesn't have the ability to cast to user-defined types.
-- This is an extremely hacky, slow, unsafe, untested, and completely unrecommended workaround.
declare @SystemTypeId tinyint,
@MaxLength smallint
select @SystemTypeId = system_type_id, @MaxLength = max_length from sys.types where name = 'your_user_defined_type_name';
declare @TypeFullName sysname = type_name(@SystemTypeId) + (case
-- char, varchar
when @SystemTypeId in (167, 175) then '(' + cast(@MaxLength as varchar) + ')'
-- nchar, nvarchar
when @SystemTypeId in (239, 231) then '(' + cast((@MaxLength / 2) as varchar) + ')'
else ''
end);
exec('select cast(something_to_be_cast as ' + @TypeFullName + ');');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.