views:

2306

answers:

2

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)

+3  A: 

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.

Jim Birchall
+2  A: 

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.

Mark Plumpton