简体   繁体   中英

SQL Server stored procedure: append values in table column based on conditions

I have a staging table with 50 columns. The last column is for storing validation result for previous 49 columns. I want to append validation results for all columns in last column. ie Out of these 49 columns there are 25 columns (eg col1, col2, col3...col25) which are mandatory. Now I want to add error messages in last column (eg col1 is mandatory, col2 is mandatory, col3 is mandatory...col25 is mandatory) if any of mandatory columns is null.

How can I do that in a stored procedure?

This doesn't sound like a smart idea. If columns 1 to 25 are mandatory, then you should think about declaring them as NOT NULL.

However, if you really want a query that adds an error message to a ValidationResults column then try this:

UPDATE YourTable SET ValidationResults = 
CASE
    WHEN (col1 is null) or (col2 is null) or (col3 is null) or (col4 is null)  -- etc
    THEN 'Your error message'
    ELSE ''
END

or simply

UPDATE YourTable SET ValidationResults = 'Your error message'
WHERE (col1 is null) or (col2 is null) or (col3 is null) or (col4 is null)  -- etc

(depending on whether you need to clear any previous error message or not).

please refer this Code . . .

Update Table_Name
SET
[Column_Status] = 
CASE 
    WHEN Column_1 IS NULL OR Column_1 = '' 
    THEN 'Column_1 is mandatory, ' ELSE '' END +
CASE 
    WHEN Column_2 IS NULL OR Column_2 = '' 
    THEN 'Column_2 is mandatory, ' ELSE '' END +

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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