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

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.default_constraints d ON t.object_id = d.parent_object_id
INNER JOIN sys.columns c ON d.parent_column_id = c.column_id AND c.object_id = t.object_id
INNER JOIN sys.types ty on ty.system_type_id = c.system_type_id 
AND ty.name in ('nvarchar', 'varchar', 'char', 'nchar')

--带维护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 [' + t.name + '] DROP CONSTRAINT [' + d.name + ']' AS drop_constraint_sql,
CASE WHEN c.is_nullable = 1 THEN
      'ALTER TABLE ' + OBJECT_NAME(c.object_id) + ' ALTER COLUMN ' + c.name + 
      CASE WHEN c.max_length < 100 THEN ' NVARCHAR(100)' ELSE ' NVARCHAR('+ CONCAT('', c.max_length)+')' END + ' NULL'
    ELSE
      'ALTER TABLE [' + OBJECT_NAME(c.object_id) + '] ALTER COLUMN ' + c.name + 
      CASE WHEN c.max_length < 100 THEN ' NVARCHAR(100)' ELSE ' NVARCHAR('+ CONCAT('', c.max_length)+')' END + ' NOT NULL'
    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.default_constraints d ON t.object_id = d.parent_object_id
INNER JOIN sys.columns c ON d.parent_column_id = c.column_id AND c.object_id = t.object_id
INNER JOIN sys.types ty on ty.system_type_id = c.system_type_id 
AND ty.name in ('nvarchar', 'varchar', 'char', 'nchar')

--不是nvarchar 或者是nvarchar  但是长度小于100
and  (ty.name!='nvarchar' or (ty.name='nvarchar' and c.max_length<100))