简体   繁体   English

SQL Server中存储过程中的数据长度验证

[英]Data length validation in stored procedure in SQL Server

I have 4 tables called A, B, C, D. These 4 tables have 10,20,30,40 columns. 我有4个表,分别称为A,B,C,D。这4个表有10、20、30、40列。 But these 4 tables are have 5 common columns with the same datatype and different lengths. 但是这4个表有5个公共列,它们具有相同的数据类型和不同的长度。

My action to be done is, I send a table of values (single row which has the values of those 5 common values also) to stored procedure. 我要执行的操作是,将值表(单行也具有这5个公共值的值)发送到存储过程。

Now I want to insert the row into a table which should be found by the table name (table name is available in the row itself). 现在,我想将该行插入到应该通过表名找到的表中(表名在行本身中可用)。 And there before I need to do data length validation. 在此之前,我需要进行数据长度验证。

It should not be like 它不应该像

if(len(@value1) > 800)

I need some different way to produce the length validation. 我需要一些不同的方法来进行长度验证。 Because in future, I may change the length of the column for some purpose. 因为将来我可能出于某些目的更改列的长度。 At the time I cannot change the value in the stored procedure. 当时我无法更改存储过程中的值。 Please give me the solution 请给我解决方案

You can use INFORMATION_SCHEMA.COLUMNS view to fetch information of the column belonging to the table . 您可以使用INFORMATION_SCHEMA.COLUMNS视图获取属于该表的列的信息。

DECLARE @ColumnLength INT

SELECT @ColumnLength  = CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME='columnName'

-- Use the variable @ColumnLength for conditons in your stored proc so need of hardcoding length

IF LEN(@value1) > @ColumnLength 
BEGIN

 -- Your statements
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM