We have SProcs which we refer to as "UpSerts" which are designed to save data from web pages.These any allow any/all columns from the table to be passed to the SProc with the assumptions that:Web input forms yield "" blank strings for 'empty' dataIt is not possible to generate a NULL value from a web formSo, all parameters to the Sproc default to NULL. If their value is NULL it can only be because it was not provided to the Sproc and it is set to NULL by default; when a column parameter is NULL the Sproc will PRESERVE any existing data in that column.Also, all parameters are in VARCHAR format, so non-varchar columns are converted to appropriate datatypes (using local variables)The reason for this is that we NEED to be able to change, say, a date from "Present" to "Empty" - someone "removes" the value from a date field, so now we have to store a NULL.Thus parameters containing EMTPY strings (rather than NULL which indicates 'no value provided') are indications to store NULL in the database.We took the decision to NOT store empty strings in the database - i.e. all empty strings become NULLs in the DB - this may not suit everyone!CREATE PROCEDURE my_SP_MyTable_Save @MyPKColumn1 varchar(nn), @MyPKColumn2 varchar(nn), -- This is actually type INT @MyColumn3 varchar(nn)=NULL, @MyColumn4 varchar(nn)=NULL -- This is actually type DATETIMEASDECLARE @int_MyPKColumn2 int, @dt_MyColumn4 datetime-- Convert non-varchar columns to appropriate typeSELECT @int_MyPKColumn2 = CASE WHEN @MyPKColumn2 = '' THEN NULL ELSE CONVERT(int, @MyPKColumn2) END, @dt_MyColumn4 = CASE WHEN @MyColumn4= '' THEN NULL ELSE CONVERT(datetime, @MyColumn4) ENDIF EXISTS ( SELECT * FROM MyTable WHERE MyPKCOlumn1 = @MyPKCOlumn1 AND MyPKCOlumn2 = @int_MyPKColumn2)BEGIN -- Update required UPDATE MyTable SET MyColumn3 = CASE WHEN @MyColumn3 = '' THEN NULL ELSE COALESCE(@MyColumn3, MyColumn3) END,-- NOTE The varchar column is used here, NOT the @dt_XXX column MyColumn4 = CASE WHEN @MyColumn4 = '' THEN NULL -- NOTE The @dt_XXX column is used here! ELSE COALESCE(@dt_MyColumn4, MyColumn4) WHERE MyPKColumn1 = @MyPKColumn1 AND MyPKColumn2 = @int_MyPKColumn2ENDELSEBEGIN -- New record, INSERT INSERT INTO MyTable ( MyPKColumn1, MyPKColumn2, MyColumn3, MyColumn4 )SELECT @MyPKColumn1, @int_MyPKColumn2, CASE WHEN @MyColumn3 = '' THEN NULL ELSE @MyColumn3 END, CASE WHEN @MyColumn4 = '' THEN NULL ELSE @dt_MyColumn4 ENDEND
Kristen