質問

Just ran into a major headache when concatenating several @varchar(max) variables together to build an email based on several different queries.

For efficiencies sake, I was using several varchars to build the email at once, rather than going through roughly the same query two or three or more times to build it using only one varchar.

This worked, right up until my varchars got to longer than 8000 characters. Then the concatenation of them all into one varchar (which I could shove into the @body parameter of msdb.dbo.sp_send_dbmail) returned "", and even LEN() wouldn't actually give me a length.

Anyhow, I've gotten around this by doing roughly the same queries several times and building the email with only one varchar(max).

TL;DR

I'm not happy with the solution. How could I have appended these varchar(max) variables to each other?

役に立ちましたか?

解決

One thing I've hit in the past which may or may not help here: SQL seems to "forget" what datatype its working with when you concatenate varchar(max). Instead of maintaining the MAX, it devolves to conventional varcharnitude, meaning truncation at 8000 characters or so. To get around this, we use the following trick:

Start with

SET @MyMaxVarchar = @aVarcharMaxValue + @SomeString + @SomeOtherString + @etc

and revise like so:

SET @MyMaxVarchar = cast(@aVarcharMaxValue as varchar(max)) + @SomeString + @SomeOtherString + @etc

Again, this may not help with your particular problem, but remembering it might save you major headaches down the road some day.

他のヒント

This may not have happened in your case, but there's a "gotcha" embedded in SQL Management Studio involving VARCHAR(MAX): SQL Studio will only output so many characters in the results grid. You can test this:

SELECT @MyLongVar, LEN(@MyLongVar)

You may find that the length of the actual data returned (most text editors can give you this) is less than the length of the data stored in the variable.

The fix is in Tools | Options | Query Results | SQL Server | Results to Grid; increase Maximum Characters Retrieved | Non XML data to some very large number. Unfortunately the maximum is 65,535, which may not be enough.

If your problem does not involve outputting the variable's value in SQL Studio, please disregard.

I have found that MS SQL silently does NOTHING when attempting to concatentate a string to a NULL value. therefore this solution always works for me:

UPDATE myTable
   SET isNull(myCol, '') += 'my text'
 WHERE myColumnID = 9999
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top