views:

94

answers:

4

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.

+1  A: 

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.

Jon
+2  A: 

I'd use

 set @bit = 1

It's safe (assigning true to a bit feels wrong) and convert just seems pointless.

ho1
+2  A: 

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)
Lieven
You are totally right
adopilot
+1, what i was thinking, but only if fin_stavke.id is unique, which seems like a reasonable assumption in this case
KM
@adopilot - printed and framed your comment. It will come in handy the next time I have an argument with my wife.
Lieven
+1  A: 

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.

Guffa