Sql-Server

更新二進製欄位

  • April 26, 2017

如何將二進製欄位從 0x54 更新到 0x46(T 到 F)?

Update dbo.table1
set field = convert(varchar,field,0x46)
where fieldID = '1'

假設該欄位是 BINARY 數據類型:

UPDATE [dbo].[Table]
SET [field] = CONVERT(BINARY,'F')
WHERE [fieldID] = 1;

這是我的概念證明:

CREATE TABLE #TempBinTable
([Identity] INT
,[BinColumn] BINARY);

INSERT INTO #TempBinTable
VALUES(1,CONVERT(BINARY,'T'));

SELECT [Identity], [BinColumn]
FROM #TempBinTable;
--RESULT
----Identity    | BinColumn
----1           | 0X54

UPDATE #TempBinTable
SET [BinColumn] = CONVERT(BINARY,'F')
WHERE [BinColumn] = CONVERT(BINARY,'T');

SELECT [Identity], [BinColumn]
FROM #TempBinTable;
--RESULT
----Identity    | BinColumn
----1           | 0X46

DROP TABLE #TempBinTable;

使用正確的數據類型聲明一個變數,分配值,並使用該值進行更新。

-- Asume VARBINARY(10) is the correct datatype
DECLARE @updateValue VARBINARY(10) = 0x46;

UPDATE dbo.table1
SET field = @updateValue
WHERE fieldID = 1;
GO

如果您想要內聯更新,請執行以下操作:

-- Asume VARBINARY(10) is the correct datatype
UPDATE dbo.table1
SET field = CONVERT(VARBINARY(10), 'F')
WHERE fieldID = 1;
GO

引用自:https://dba.stackexchange.com/questions/146034