A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Thursday, February 22, 2018

Altering table types, part 2

Altering table types - a compatibility guide

In yesterday's post, I altered a table type. Pray I don't alter them further. What else is incompatible with an integer column? It's just a morbid curiosity at this point as I don't recall having ever seen this after working with SQL Server for 18 years. Side note, dang I'm old

How best to answer the question, by interrogating the sys.types table and throwing operations against the wall to see what does/doesn't stick.

DECLARE
    @Results table
(
    TypeName sysname, Failed bit, ErrorMessage nvarchar(4000)
);

DECLARE
    @DoOver nvarchar(4000) = N'DROP TABLE IF EXISTS dbo.IntToTime;
CREATE TABLE dbo.IntToTime (CREATE_TIME int);'
,   @alter nvarchar(4000) = N'ALTER TABLE dbo.IntToTime ALTER COLUMN CREATE_TIME @type'
,   @query nvarchar(4000) = NULL
,   @typeName sysname = 'datetime';

DECLARE
    CSR CURSOR
FORWARD_ONLY
FOR
SELECT 
    T.name
FROM
    sys.types AS T
WHERE
    T.is_user_defined = 0

OPEN CSR;
FETCH NEXT FROM CSR INTO @typeName
WHILE @@FETCH_STATUS = 0
BEGIN
    BEGIN TRY   
        EXECUTE sys.sp_executesql @DoOver, N'';
        SELECT @query = REPLACE(@alter, N'@type', @typeName);
        EXECUTE sys.sp_executesql @query, N'';
        
        INSERT INTO
            @Results
        (
            TypeName
        ,   Failed
        ,   ErrorMessage
        )
        SELECT @typeName, CAST(0 AS bit), ERROR_MESSAGE();
    END TRY
    BEGIN CATCH
        INSERT INTO
            @Results
        (
            TypeName
        ,   Failed
        ,   ErrorMessage
        )
        SELECT @typeName, CAST(1 AS bit), ERROR_MESSAGE()
    END CATCH
    FETCH NEXT FROM CSR INTO @typeName
END
CLOSE CSR;
DEALLOCATE CSR;

SELECT
*
FROM
    @Results AS R
ORDER BY
    2,1;
TypeNameFailedErrorMessage
bigint0
binary0
bit0
char0
datetime0
decimal0
float0
int0
money0
nchar0
numeric0
nvarchar0
real0
smalldatetime0
smallint0
smallmoney0
sql_variant0
sysname0
tinyint0
varbinary0
varchar0
date1Operand type clash: int is incompatible with date
datetime21Operand type clash: int is incompatible with datetime2
datetimeoffset1Operand type clash: int is incompatible with datetimeoffset
geography1Operand type clash: int is incompatible with geography
geometry1Operand type clash: int is incompatible with geometry
hierarchyid1Operand type clash: int is incompatible with hierarchyid
image1Operand type clash: int is incompatible with image
ntext1Operand type clash: int is incompatible with ntext
text1Operand type clash: int is incompatible with text
time1Operand type clash: int is incompatible with time
timestamp1Cannot alter column 'CREATE_TIME' to be data type timestamp.
uniqueidentifier1Operand type clash: int is incompatible with uniqueidentifier
xml1Operand type clash: int is incompatible with xml

No comments: