问题
So I need to update a text field. Neither the UPDATE statement or the WRITETEXT statement work when used below
CREATE TABLE MyTable (IDField int, MyField text)
INSERT INTO MyTable (IDField) SELECT 1
DECLARE @Data1 varchar(8000), @Data2 varchar(8000), @ptrval binary(16)
SELECT @Data1 = REPLICATE('1',8000)
SELECT @Data2 = REPLICATE('2',8000)
-- this sets MyField to string of only 8000 characters
UPDATE MyTable SET MyField = @Data1 + @Data2 WHERE IDField = 1
SELECT @ptrval = TEXTPTR(MyField )
FROM MyTable
WHERE IDField = 1
-- this causes an error: Incorrect syntax near '+'.
--WRITETEXT MyTable.MyField @ptrval @Data1 + @Data2
How am I supposed to do this when local variables cannot be of type TEXT? (If I had SSQL Server 2005 I would use varchar(max) - but I don't)
回答1:
Try using UPDATETEXT instead
WRITETEXT MyTable.MyField @ptrval @Data1
UPDATETEXT MyTable.MyField @ptrval 8000 NULL @Data2
The insert offset is zero based so 8000 should write into the 8001st character. The delete offset is null as a value of NULL deletes all data from the insert_offset position to the end of the existing text.
Ref: http://msdn.microsoft.com/en-us/library/ms189466.aspx
Do not forget nvarchar (which you should use with ntext field) have a maximum capacity of half the varchar fields that you are using so your block sizes need to be reduced to 4000 in that case.
回答2:
the values will actually vary in length so I will try it like this tomorrow:
WRITETEXT MyTable.MyField @ptrval @Data1
UPDATETEXT MyTable.MyField @ptrval Len(@Data1) NULL @Data2
the above worked but I had to calculate the length first:
WRITETEXT MyTable.MyField @ptrval @Data1
SET @Len = LEN(@Data1)
UPDATETEXT MyTable.MyField @ptrval @Len NULL @Data2
not sure why you can't use a function like LEN() where a parameter is expected.
回答3:
I had a hard time with this one.
I was trying to save long strings (actually rich text box contents) to a ntext feild.
The solution turned out to be fairly simple.
SQLst = "UPDATE Test SET Text = cast (@value as ntext)" & _
" WHERE Num = 3 "
Debug.Print(SQLst.ToString)
Dim cnn As New SqlServerCe.SqlCeConnection(Tcon)
Dim cmd = New SqlCeCommand(SQLst, cnn)
cmd.Parameters.AddWithValue("@value", strQuestionQUESTION)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Note: strQuestionQUESTION was about 3000 characters or formatting code and text. "Num" is just an integer field in the "Test" database which also contain the ntext field name "Text"
来源:https://stackoverflow.com/questions/204170/how-to-update-a-text-or-ntext-field-in-sql-server-2000