Skip to content

Instantly share code, notes, and snippets.

@IanKemp
Last active June 1, 2020 14:23
Show Gist options
  • Save IanKemp/f63730ab735cf7f8fe5ce14a344ba742 to your computer and use it in GitHub Desktop.
Save IanKemp/f63730ab735cf7f8fe5ce14a344ba742 to your computer and use it in GitHub Desktop.
-- 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