Regarding to SQL performance.
I have a scalar valued function for checking some specific condition in base, it returns BIT value for True or False.
I now do not know how I should fill @BIT parameter
If I write.
set @bit = convert(bit,1)
or
set @bit = 1
or
set @bit='true'
function will work anyway but I do not know which method is recommended for daily use.
Another question, I have table in my base with around 4 million records, daily insert is about 4K records in that table.
Now I want to add CONSTRAINT on that table with scalar valued function that I mentioned already
Something like this
ALTER TABLE fin_stavke
ADD CONSTRAINT fin_stavke_knjizenje CHECK ( dbo.fn_ado_chk_fin(id)=convert(bit,1))
where "id" is the primary key of table fin_stavke and dbo.fn_ado_chk_fin looks like
create FUNCTION fn_ado_chk_fin
(
@stavka_id int
)
RETURNS bit
AS
BEGIN
declare @bit bit
if exists (select * from fin_stavke where id=@stavka_id and doc_id is null and protocol_id is null)
begin
set @bit=0
end
else
begin
set @bit=1
end
return @bit;
END
GO
Will this type and method of checking constraint will affect badly performance on my table and SQL at all ?
If there is also better way to add control on this table please let me know.
I might be wrong but from the looks of it, it seems you only want to check that not both doc_id
and protocol_id
are NULL
?
You can add a table constraint to achieve this.
ALTER TABLE fin_stavke
ADD CONSTRAINT fin_stavke_knjizenje CHECK ( doc_id IS NOT NULL OR protocol_id IS NOT NULL)
I'd use
set @bit = 1
It's safe (assigning true to a bit feels wrong) and convert just seems pointless.
I've always seen bit used as 1 or 0. I'd stick with that. Everyone will know what you're doing.
That constraint is going to affect the performance of your inserts but not by much since you're be seeking to the primary key of the table. It's probably the cheapest lookup you can do.
A bit variable can be set with an integer value:
set @bit = 1
Sometimes you want an actual bit value to avoid the implicit conversion, then you can do an excplicit conversion:
set @bit = cast(1 as bit)
When assigning it to a variable there is no practical difference, but in a query the conversion would happen when the query is parsed rather than when it's executed. I have used it a few times and got actual performance differences.
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.