• ScottPletcher (6/30/2016)


    Jeff Moden (6/24/2016)

    Shifting gears a bit and depending on how that's used, it could become a performance problem due to the implicit conversions of the string literals. Since @database2 has been declared as NVARCHAR, the literals should also be made to be NVARCHAR. Like this...

    DECLARE @database2 NVARCHAR(100);

    SET @database2 = NULL

    ;

    DECLARE @dbs TABLE (DBname NVARCHAR(100))

    ;

    INSERT INTO @dbs

    VALUES (N'A'),(N'B'),(N'C')

    ;

    SELECT @database2 = COALESCE(@database2 + N',', N' ') + DBname

    FROM @dbs

    ;

    SELECT @database2

    ;

    I strongly recommend against explicitly making literals nvarchar. The resulting implicit conversion is truly negligible overhead anyway. The real issue is if the column type changes to varchar, because then you explicitly forcing an nvarchar string will force an implicit column conversion, which will be many, many orders of magnitude worse than the implicit conversions of literal strings.

    And there is always an exception, such as actually using Unicode constants. If a column or variable is defined as an NVARCHAR data type there is NOTHING wrong with prepending the string with an N to ensure that it is interpreted properly.

    Using semicolons as a begininator is one of my pet peeves, but so is telling people they should never use the N'' format for string constants.