如何在SQL Server中创建验证 [英] How to create validation in SQL server

查看:88
本文介绍了如何在SQL Server中创建验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我需要通过给出错误消息验证我的表中的列与特定字段是否必须,如何在SQL Server中实现此目的。



我尝试过:



我需要验证表格中的列一个特定的字段应该是强制性的,给出一条错误消息我如何在SQL Server中实现这一点。

Hi All,
I need to Validate a column in my table with the a particular field should be mandatory ,by giving a error message How can I achieve this in SQL Server.

What I have tried:

I need to Validate a column in my table with the a particular field should be mandatory ,by giving a error message How can I achieve this in SQL Server.

推荐答案

见这里:使用检查约束来验证SQL Server中的数据 [ ^ ]

但一般来说,我更喜欢在应用程序代码中验证并仅将有效数据传递给SQL。这样,错误可以更具体地针对用户,并且只能帮助改善输入。
See here: Using Check Constraints to Validate Data in SQL Server[^]
But generally, I prefer to validate in application code and only pass valid data to SQL. That way, the error can be more specifically targeted for the user and that can only help improve input.


基于评论中的代码

based on the code in comments
declare @error int
declare @error_message nvarchar (200)
declare @ItemCode nvarchar (200)

if not exists( SELECT * FROM IGN1 WHERE [ItemCode] Like 'AP%' OR [ItemCode] Like 'ZP%' ) 
BEGIN
SET @error=-1
SET @error_message= 'This Field is Mandatory'
select @error_message
END





EXISTS(Transact-SQL) [ ^ ]


这篇关于如何在SQL Server中创建验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆