t sql – Concatenated string gets truncated


I have a query that i am writing to convert some heap tables with primary keys into clustered tables, but the string that i’m generating truncates on objects past a certain length it seems.

SELECT 
    --t.name,
 --   t.schema_id,
 --   t.type,
 --   t.type_desc,
 --   i.name,
 --   i.type,
 --   i.type_desc,
 --   i.is_primary_key,
    --c.name,
    'print ''dropping index on dbo.' + CAST(t.name AS VARCHAR(MAX)) + ''';' + CAST(CHAR(10) AS VARCHAR(MAX)) + CAST(CHAR(13) AS VARCHAR(MAX))  + 
    'drop index ' + CAST(i.name AS VARCHAR(MAX)) + ' on dbo.' + CAST(t.name AS VARCHAR(MAX)) + ';' + CAST(CHAR(10) AS VARCHAR(MAX)) + CAST(CHAR(13) AS VARCHAR(MAX)) +
    'go' + CAST(CHAR(10) AS VARCHAR(MAX)) + CAST(CHAR(13) AS VARCHAR(MAX)) +
    'print ''creating clustered primary key on dbo.' + CAST(t.name AS VARCHAR(MAX)) + ''';' + CAST(CHAR(10) AS VARCHAR(MAX)) + CAST(CHAR(13) AS VARCHAR(MAX)) +
    'alter table dbo.' + CAST(t.name AS VARCHAR(MAX)) + ' add constraint ' + CAST(i.name AS VARCHAR(MAX)) + ' primary key clustered (' + CAST(c.name AS VARCHAR(MAX)) + ');'
FROM sys.tables t
    INNER JOIN sys.indexes i
        ON i.object_id = t.object_id
    INNER JOIN sys.index_columns ic
        ON i.object_id = ic.object_id
            AND i.index_id = ic.index_id
    INNER JOIN sys.columns c
        ON t.object_id = c.object_id
            AND ic.index_column_id = c.column_id
WHERE i.type = 2
    AND t.object_id NOT IN
(
    SELECT distinct t.object_id AS tableid
    FROM sys.tables t
        INNER JOIN sys.indexes i
            ON t.object_id = i.object_id
    WHERE i.type  = 1
)
ORDER BY t.name,
    i.index_id

As you can see i tried wrapping all of the columns that i’m using in a cast statement, but it hasn’t helped. I’m not really sure why this isn’t working.

example of the complete code:

print 'dropping index on dbo.Account';

drop index PK_Account on dbo.Account;

go

print 'creating clustered primary key on dbo.Account';

alter table dbo.Account add constraint PK_Account primary key clustered (Id);

example of the truncated code:

drop index PK_ALongerTableNameABC on dbo.ALongerTableNameABC;

go

print 'creating clustered primary key on dbo. ALongerTableNameABC';

alter table dbo.ALongerTableNameABC add constraint PK_ALongerTableNa

I am grabbing the generated code by running the query with Results to Text.