Skip to content

SQL Server: Shim enums as table/key or as custom types with rules #6823

Open

Description

@josh-hemphill

Problem

I currently can't create enums when working with the SqlServer provider, which means I have to design my schema differently and won't get any intellisense or type information during development when working with "enum" fields.

Suggested solution

I can think of a few options.

The creation and maintenance of a joined table containing the enum could be obfuscated and queries could just automatically join to replace the enum, though this may make problems for raw queries and anyone doing something manual with the database.

After thinking it over a bit though, perhaps the option with the least downsides would be creating the column with a CHECK parameter or as a custom type with an @list rule, and storing the enum key just as a string directly.
e.g.

CREATE RULE [dbo].[list_rule] AS @list IN ('USER', 'ADMIN'); 
GO
CREATE TYPE [dbo].[TestType] FROM VARCHAR(5) NOT NULL
GO
EXEC sys.sp_bindrule @rulename=N'[dbo].[list_rule]', @objname=N'[dbo].[TestType]' , @futureonly='futureonly'
GO
CREATE TABLE dbo.Table_1
	(
	/* You could create a reusable "Enum" by creating it as a type,
		or just adding the check constraint for a single one */
	Test dbo.TestType NULL,
	Test2 nchar(5) NOT NULL 
		CONSTRAINT Test2_Enum CHECK (Test2 IN('USER', 'ADMIN')),
	)  ON [PRIMARY]
GO

Alternatives

At the moment, I'm considering creating a seed script to populate my tables that would otherwise be enums, but this doesn't provide intellisense during development and means I have to build my schema specially for MSSQL.

Activity

  1. added
    kind/feature
    topic: sql server
    on Apr 28, 2021
  2. JasonAtallah commented on Aug 6, 2022

    @JasonAtallah

    Are there any plans to move forward with this?

  3. changed the title [-][Feature Request] SqlServer - shim enums as table/key or as custom types with rules[/-] [+]SQL Server: Shim enums as table/key or as custom types with rules[/+] on Aug 8, 2022
  4. Katli95 commented on Aug 21, 2022

    @Katli95

    I'm not qualified to comment on if this would be the best way, but I'd love having access to something like an enum with the SQL Server Provider!

  5. added
    topic: enum
    on Oct 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/featuretopic: enumtopic: shimmingtopic: sql server

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions