简体   繁体   中英

Fully transparent CLR types in SQL Server

I would like to take advantage of User Defined Types that can be created in a .NET assembly and then imported to SQL Server to perform a transparent operation like for example encryption. Encryption would be handled in Parse method while decryption in the ToString method. It would be a change on working system so I would like not to modify the code that already uses these tables.

Given I have a following table, where EncryptedString is a .NET type:

CREATE TABLE dbo.EncryptedStrings 
(ID int IDENTITY(1,1) PRIMARY KEY, EncryptedStringValue EncryptedString)

I can then insert values into that table, like it's a normal string column - existing code could be maintained (Parse method in .NET code is then executed – which performs Encryption in my case).

INSERT INTO dbo.EncryptedStrings (EncryptedStringValue) VALUES ('AAA');
INSERT INTO dbo.EncryptedStrings (EncryptedStringValue) VALUES ('BBB');

But, when I do a simple SELECT :

SELECT * FROM dbo.EncryptedStrings

Then I receive binary serialized representation, like:

在此处输入图片说明

I need to explicitly invoke ToString or CAST it to VARCHAR to make ToString be executed:

SELECT ID, EncryptedStringValue.ToString() FROM EncryptedStrings

在此处输入图片说明

Is there any way to configure Server so that it always showed ToString representation, and the following SELECT queries always returned the same results?

SELECT ID, EncryptedStringValue FROM dbo.EncryptedStrings
SELECT ID, EncryptedStringValue.ToString() FROM EncryptedStrings

There are a couple of options, at least one of which has been mentioned so far:

  1. Create a view that calls the appropriate method on the CLR UDT (eg ToString()).
  2. Create a computed (possibly persisted) on the table whose definition is a call to the appropriate method (see above)

Other than that, I don't think there's a way to say "call this method whenever this value is accessed".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM