﻿--同步重阅申请表结构后，再维护该字段

UPDATE VisitTaskReReading
SET TrialId = VisitTask.TrialId
FROM VisitTaskReReading 
INNER JOIN VisitTask ON VisitTaskReReading.OriginalReReadingTaskId = VisitTask.Id;

delete VisitTaskReReading where TrialId is NULL


--数据库列字符串列 长度 
SELECT t.name AS table_name, 
       c.name AS column_name,
       d.name AS constraint_name,
       ty.Name as typeName, 
       c.max_length as length
FROM sys.tables t
INNER JOIN sys.columns c ON  c.object_id = t.object_id
LEFT JOIN sys.default_constraints d ON d.parent_object_id = c.object_id AND d.parent_column_id = c.column_id
INNER JOIN sys.types ty on ty.system_type_id = c.system_type_id 
AND ty.name in ('nvarchar', 'varchar', 'char', 'nchar')
WHERE c.max_length < 100 AND c.max_length > 0

--带维护sql 的查询

SELECT t.name AS table_name, 
       c.name AS column_name,
       d.name AS constraint_name,
       ty.Name as typeName, 
       c.max_length as length,
       'ALTER TABLE ' + QUOTENAME(t.name) + ' DROP CONSTRAINT [' + d.name + ']' AS drop_constraint_sql,			 
       CASE WHEN c.max_length = -1 THEN 'ALTER TABLE ' + QUOTENAME(t.name) + ' ALTER COLUMN ' + QUOTENAME(c.name) + ' NVARCHAR(MAX)' +  CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END 
            WHEN c.max_length > 0 AND c.max_length < 100 THEN 'ALTER TABLE ' + QUOTENAME(t.name) + ' ALTER COLUMN ' + QUOTENAME(c.name) + ' NVARCHAR(' + CAST(100 AS VARCHAR(10)) + ')' +  CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END 
            WHEN c.max_length = 8000 THEN 'ALTER TABLE ' + QUOTENAME(t.name) + ' ALTER COLUMN ' + QUOTENAME(c.name) + ' NVARCHAR(' + CAST(4000 AS VARCHAR(10)) + ')' +  CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END 
            ELSE 'ALTER TABLE ' + QUOTENAME(t.name) + ' ALTER COLUMN ' + QUOTENAME(c.name) + ' ' + ty.name + '(' + CAST(c.max_length AS VARCHAR(10)) + ')' +  CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END 
       END AS AlterColumnSQL,
       'ALTER TABLE ' + QUOTENAME(t.name) + ' ADD CONSTRAINT ' +'DF_'+t.name+ '_'+ c.name +  ' DEFAULT ' + d.definition + ' FOR ' + QUOTENAME(c.name) AS add_constraint_sql
FROM sys.tables t
INNER JOIN sys.columns c ON  c.object_id = t.object_id
LEFT JOIN sys.default_constraints d ON d.parent_object_id = c.object_id AND d.parent_column_id = c.column_id
INNER JOIN sys.types ty on ty.system_type_id = c.system_type_id 
AND ty.name in ('nvarchar', 'varchar', 'char', 'nchar')
and (ty.name != 'nvarchar' or (ty.name = 'nvarchar' and (c.max_length = -1 or (c.max_length < 100 and c.max_length > 0))))