簡體   English   中英

在SQL Server中將數據類型Varchar更改為Varbinary(max)

[英]Change Data Type Varchar To Varbinary(max) In SQL Server

我想使用此查詢在SQL Server中將varchar更改為varbinary(max)

ALTER TABLE  [dbo].[Attachments]
ALTER COLUMN [Content]  varbinary(max)  NOT NULL

但是這會引發以下異常:

不允許從數據類型varchar到varbinary(max)的隱式轉換。 使用CONVERT函數運行此查詢

在這種情況下我應該改變什么?

你確定要varbinary(max)嗎? 如果是這樣,我相信您需要按步驟執行此操作:

ALTER TABLE Attachments
ADD Content2 varbinary(max)

UPDATE Attachments
SET Content2 = CONVERT(varbinary(MAX),Content)

ALTER TABLE Attachments
DROP COLUMN Content

sp_RENAME 'Attachments.[Content2]' , '[Content]', 'COLUMN'

根據表的性質,通過選擇將其轉換為以下內容可能會更快:

SELECT Content = CAST(Content AS VARBINARY(MAX))
       ,other fields
INTO NewTable
FROM OldTable

然后刪除舊表並重命名新表:

DROP TABLE OldTable
GO
SP_RENAME 'NewTable', 'OldTable'

您需要暫存流程:

    ALTER TABLE  [dbo].[Attachments]
    ADD [TempContent]  varbinary(max) 

go

    UPDATE Attachements SET TempContent = CAST(Content as VARBINARY)
go 

    ALTER TABLE  [dbo].[Attachments]
    DROP COLUMN [Content] 

go  
    sp_RENAME 'Attachements.[TempContent ]' , '[Content ]', 'COLUMN'

go

您也可以在SQL Server Management Studio中執行此操作,如果啟動分析器,它將顯示它使用的代碼(始終有用)

將文件插入數據庫時​​使用此方法:

SqlCommand cmd = new SqlCommand("Insert into tblJobSeeker Values('"+txtUserName.Text+"',@Data)",con);
cmd.Parameters.AddWithValue("@Data",Filesize);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM