Question

I don't know if what I want to do is possible or not, and I'm just curious.

I've got a User Defined Type of say MyType which is a TINYINT along with a RULE which states that the value permissible must be between 0 and 3.

-- Existing UDT & Rule which work
CREATE TYPE [MySchema].[MyTypes]
FROM [TINYINT]

CREATE RULE [MySchema].[MyTypes_Rule] AS
@Range BETWEEN 0 AND 3

sp_bindrule 'MySchema.MyTypes_Rule', 'MySchema.MyTypes'

What I'd like to know is would it be possible to add an additional rule/functionality which would allow me to create an additional rule which would take an NVARCHAR value and if it's within that range convert it to the appropriate TINYINT value.

CREATE RULE [MySchema].[MyTypes_NVARCHAR_Rule1] AS
@InValues IN (N'N', N'A', N'B', N'C')

CREATE RULE [MySchema].[MyTypes_NVARCHAR_Rule1] AS
@InValues IN (N'No Choice', N'Choice A', N'Choice B', N'Choice C')

And then do some type of conversion from 'Choice A' or 'A' to a value of 1, 'Choice B' or 'B' to a value of 2, etc,etc, etc.

The below script would be similar to the functionality I am wanting to do where a string is converted to a permissible value.

CREATE TABLE [MyTable]
( [MyValue] BIT,
  [Description] NVARCHAR(20) )
GO

INSERT INTO [MyTable]
( [MyValue], [Description] )
SELECT 0, 'Enterered as 0' -- false
UNION
SELECT 1, 'Enterered as 1' -- true
UNION
SELECT CAST(0 AS BIT), 'Enterered as CAST(0 AS BIT)' -- false
UNION
SELECT CAST(1 AS BIT), 'Enterered as CAST(1 AS BIT)' -- true
UNION
SELECT CAST('false' AS BIT), 'Enterered as CAST(''false'' AS BIT)' -- false
UNION
SELECT CAST('true' AS BIT), 'Enterered as CAST(''true'' AS BIT)' -- true
Was it helpful?

Solution

No, nothing like that is possible in plain T-SQL unfortunately.

You could create a CLR User defined function which took a sql_variant, and then do type testing within that, however, I would question the necessity for it. Usually you would want to do this sort of translation in the code that runs in your user interface, such that you are ready with a fixed data-type by the time you get to your business logic layer, let alone your database.

Incidentally, CREATE RULE is being deprecated - and has been on the 'this feature will be removed in a future version' status for a long time. So far, I haven't seen any alternatives which would let you define a CHECK constraint on user defined types. That may be some of the reason why it's not actually been deprecated yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top