In some languages (C# for example), you can coalesce to a throw expression, E.G.
string someValue = MyFunctionThatMightReturnNull() ?? throw new Exception("null value");
Wondering if there is any syntax like this in SQL Server.
This is not valid syntax, but it illustrates the idea:
INSERT INTO "MyTable" ("MyColumn")
VALUES (COALESCE(MyFunction(), THROW 50005, N'An error occurred', 1));
I understand that I can make the column NOT NULL, but in my use case the column should be NULL.
I also understand that I can use a block statement like
DECLARE @myVar VARCHAR(MAX);
SELECT @myVar = MyFunction();
IF (@myVar IS NULL)
BEGIN
THROW 50005, N'An error occurred', 1;
END
INSERT INTO "MyTable" ("MyColumn") VALUES (@myVar);
While this works, it is limited because you can't use it with INSERT SELECT, E.G.
INSERT INTO "MyTable" ("MyColumn")
SELECT COALESCE("MyOtherTableColumn", THROW 50005, N'An error occurred', 1)
FROM "MyOtherTable";
Wondering if there is any syntax that accomplishes this.
select isnull(somecolumn, cast('somecolumn cannot be null' as int))or something like this which generates another error but still delivers the message inside it, mostly this is good for functions which cannot easily signal errors.MyColumnshouldn't beNULL, which can checked with aCONSTRAINT?