Click here to Skip to main content
15,913,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 8-Sep-16 20:08pm
Comments
Karthik_Mahalingam 9-Sep-16 1:57am    
are you using stored procedure?
win or web?
Member 12605293 9-Sep-16 2:00am    
Hi Karthik,
Thanks for your Quick reply,This is my Query
declare @error int
declare @error_message nvarchar (200)
declare @ItemCode nvarchar (200)
SELECT * FROM IGN1
WHERE [ItemCode] Like 'AP%' OR [ItemCode] Like 'ZP%'
IF ISNULL ([@ItemCode],0)!=0
BEGIN
SET @error=-1
SET @error_message= 'This Field is Mandatory'
END
Karthik_Mahalingam 9-Sep-16 2:05am    
@itemcode is not assigned
check my solution

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.
 
Share this answer
 
based on the code in comments
SQL
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)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900