使用数组

时间:2016-07-17 03:11:56

标签: sql sql-server stored-procedures

我的表SurnameFirstNameMiddleNameCurrAddress中有四列。有没有办法可以使用数组动态存储列名并获取每列的最大长度?比如说,在四个字段中,我只需要SurnameFirstName个最大长度。我的下面的代码每个事务只显示一列。任何帮助是极大的赞赏。谢谢!

 ALTER PROCEDURE [dbo].[sp_getColumnLength]
     @colval nvarchar(50),
     @tblval nvarchar(50)
 AS
 BEGIN
     SELECT 
         character_maximum_length as 'Max Length'
     FROM 
         information_schema.columns
     WHERE 
         column_name = @colval 
         AND table_name = @tblval
 END
 GO

2 个答案:

答案 0 :(得分:0)

你有一个本机功能:

     select COL_LENGTH('TABLENAME', 'COLUMNNAME')

答案 1 :(得分:0)

您可以使用表值参数代替数组,请参阅https://msdn.microsoft.com/en-gb/library/bb510489(v=sql.110).aspx

microsoft的示例对我不起作用,但以下代码

USE AdventureWorksdw2012;
GO

/* Create a table type. */
drop type t1
go
CREATE TYPE t1 AS TABLE 
( tabname CHAR(50)
, colname char(50) );
GO

/* Create a procedure to receive data for the table-valued parameter. */
CREATE PROCEDURE dbo. usp_InsertProductionLocation
    @TVP [db_datareader].[t1] readonly
    AS 

 BEGIN
     SELECT 
         character_maximum_length as 'Max Length'
     FROM 
         @TVP
     join information_schema.columns on table_name = tabname and column_name = colname

 END
 GO

/* Declare a variable that references the type. */
DECLARE @TVP AS t1;

/* Add data to the table variable. */
insert into @TVP values ('dimcustomer','title'),('dimcustomer','firstname')

/* Pass the table variable data to a stored procedure. */
EXEC usp_InsertProductionLocation @TVP;
GO

微软的问题似乎是t1需要在存储过程中完全合格。