Sample code for 30+ languages & platforms
SQL Server

StringBuilder SetNth

Demonstrates the SetNth method.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    -- The SetNth method is handy for setting a part of a delimited string.
    -- For example:

    DECLARE @sb int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sb OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @success int
    EXEC sp_OAMethod @sb, 'Append', @success OUT, 'red,blue,"green,purple",,yellow'

    DECLARE @delimiterChar nvarchar(4000)
    SELECT @delimiterChar = ','
    DECLARE @exceptDoubleQuoted int
    SELECT @exceptDoubleQuoted = 1
    DECLARE @exceptEscaped int
    SELECT @exceptEscaped = 1

    EXEC sp_OAMethod @sb, 'SetNth', @success OUT, 2, 'magenta', @delimiterChar, @exceptDoubleQuoted, @exceptEscaped
    -- Prints "red,blue,magenta,,yellow"
    EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    EXEC sp_OAMethod @sb, 'SetNth', @success OUT, 3, 'orange', @delimiterChar, @exceptDoubleQuoted, @exceptEscaped
    -- Prints "red,blue,magenta,orange,yellow"
    EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    -- What happens if we start with an empty string?
    EXEC sp_OAMethod @sb, 'Clear', NULL

    EXEC sp_OAMethod @sb, 'SetNth', @success OUT, 2, 'apple', @delimiterChar, @exceptDoubleQuoted, @exceptEscaped
    -- Prints ",,apple"
    EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    EXEC sp_OAMethod @sb, 'SetNth', @success OUT, 0, 'orange', @delimiterChar, @exceptDoubleQuoted, @exceptEscaped
    -- Prints "orange,,apple"
    EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    EXEC sp_OAMethod @sb, 'SetNth', @success OUT, 1, 'banana', @delimiterChar, @exceptDoubleQuoted, @exceptEscaped
    -- Prints "orange,banana,apple"
    EXEC sp_OAMethod @sb, 'GetAsString', @sTmp0 OUT
    PRINT @sTmp0

    EXEC @hr = sp_OADestroy @sb


END
GO