请输入以下代码:
DECLARE @EncryptedPassword VARBINARY(8000) = ENCRYPTBYPASSPHRASE('ABCD','password')
DECLARE @Setting AS TABLE (ID INT, Value VARCHAR(MAX))
INSERT INTO @Setting VALUES (1, 'true')
INSERT INTO @Setting VALUES (2, @EncryptedPassword)
SELECT * FROM @Setting
@Setting
表可以包含具有多种数据类型的数据。如我所见,它存储了值。但是无法使用SELECT
命令来检索它。我该如何实现?
答案 0 :(得分:1)
正如我在评论中所说,我强烈建议您旋转设置表,并停止对所有内容进行严格键入:
DECLARE @EncryptedPassword VARBINARY(8000) = ENCRYPTBYPASSPHRASE('ABCD','password')
DECLARE @Setting AS TABLE (
Lock char(1) not null default 'X' primary key check (Lock='X'),
SomethingBoolean bit not null,
Password varbinary(8000) not null)
INSERT INTO @Setting (SomethingBoolean, Password) VALUES
(1,@EncryptedPassword)
SELECT * FROM @Setting
结果:
Lock SomethingBoolean Password
---- ---------------- -----------------------------------------------------------------------------------------------------------
X 1 0x02000000588C2EB2C67DED10B7828C05500008DB1B1E53EFF63168EC607CA80CA2A1147B75F0A9D50F6B95C810D6DCED37AE8186
这意味着设置实际上是使用正确的数据类型存储的。我们不仅可以依靠类型检查和null检查来确保设置正确,还可以根据需要对单个设置应用单独的CHECK
约束。
({Lock
只是为了确保该表仅包含1行)
答案 1 :(得分:0)
尝试更改表结构,并在检索DECRYPT值时尝试将其转换为Varbinary列Nvarchar.ENCRYPTBYPASSPHRASE或DECRYPTBYPASSPHRASE需要2个或更多参数才能得出结果
DECLARE @Setting AS TABLE (ID INT,Value VARBINARY(8000))
INSERT INTO @Setting
SELECT 1,ENCRYPTBYPASSPHRASE('password',N'ABCD')
SELECT * FROM @Setting
SELECT CONVERT(NVARCHAR(4000),DECRYPTBYPASSPHRASE('password',Value)) FROM @Setting
答案 2 :(得分:0)
您可以仅添加加密标志:
DECLARE @EncryptPhrase NVARCHAR(100) = 'ABCD'
DECLARE @Setting AS TABLE (ID INT, Value NVARCHAR(MAX), IsEncrypted BIT)
INSERT INTO @Setting VALUES (1, 'true', 0)
INSERT INTO @Setting VALUES (2, ENCRYPTBYPASSPHRASE(@EncryptPhrase,N'password'), 1)
SELECT * FROM @Setting
SELECT
ID
,CASE
WHEN IsEncrypted = 1 THEN CAST(DecryptByPassPhrase(@EncryptPhrase, CAST(Value AS VARBINARY(MAX))) as NVARCHAR(MAX))
ELSE Value
END
FROM @Setting