将表名作为参数传递

时间:2018-11-21 07:24:09

标签: sql sql-server

我想将表名作为参数传递,并通过该表的列长+ 50更改该表的所有列大小。

alter PROCEDURE dbo.testsp
  @tablename varchar(100)
AS
BEGIN
DECLARE 
@totalWeight TABLE (columnnames nvarchar(100));
INSERT INTO @totalWeight (columnnames)
SELECT name FROM sys.columns
 WHERE object_id = object_id(@tablename);
END
GO

2 个答案:

答案 0 :(得分:2)

此查询在最后一列中返回您的更改语句。然后,您可以通过动态sql运行它们。

SELECT 
    tbl.name 'Table Name',
   c.name 'Column Name',
   t.name,  
   c.max_length 'Max Length in Bytes',
   c.precision ,
   c.scale ,
   c.is_nullable,
   q1.*,
       'alter table ['
       +tbl.name
       +'] alter column ['
       +c.name
       +'] '
       +t.name
       +'('+
       convert(nvarchar(1000),  CASE WHEN t.name IN ('nchar','nvarchar') THEN  c.max_length/2 ELSE c.max_length END +50)
       +') '
        + case c.is_nullable when 0 then ' not null' else ' null' end
    as 'Alteration statement'
FROM    
   sys.columns c
INNER JOIN 
   sys.types t ON c.user_type_id = t.user_type_id
inner join sys.tables tbl on tbl.object_id=c.object_id
CROSS APPLY
(
    select
        t.name +
        CASE WHEN t.name IN ('char', 'varchar','nchar','nvarchar') THEN '('+

                    CASE WHEN c.max_length=-1 THEN 'MAX'

                        ELSE CONVERT(VARCHAR(4),

                                    CASE WHEN t.name IN ('nchar','nvarchar')

                                    THEN  c.max_length/2 ELSE c.max_length END )

                        END +')'

                WHEN t.name IN ('decimal','numeric')

                        THEN '('+ CONVERT(VARCHAR(4),c.precision)+','

                                + CONVERT(VARCHAR(4),c.Scale)+')'

                        ELSE '' END
        + case c.is_nullable when 0 then ' not null' else ' null' end
        as [DDL name before]
)q1
where t.name IN ('char', 'varchar','nchar','nvarchar') and c.max_length>-1

答案 1 :(得分:0)

运行以下查询示例,它将创建一堆ALTER语句。将结果复制粘贴到新的查询窗口中,然后再次运行。如果需要,请从sys.types添加其他数据类型。

SELECT 'ALTER TABLE [' + s.name + '].[' + t.name + '] ALTER COLUMN [' +
       c.name + '] ' + ty.name + '(' + CAST(c.max_length + 50 AS nvarchar(10)) + ') ' +
       CASE WHEN c.is_nullable = 1 THEN 'NULL' ELSE 'NOT NULL' END + ';'
FROM sys.tables t 
     INNER JOIN sys.columns c ON t.object_id = c.object_id
     INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
     INNER JOIN sys.types ty ON c.system_type_id = ty.system_type_id
WHERE t.type = 'U' AND
      c.system_type_id IN (167 /*varchar*/, 231 /*nvarchar*/)