Best Searching Criteria
I have a table
GO
CREATE TABLE [dbo].[Speech]
(
[SpeechId] [int] IDENTITY(1,1) NOT NULL CONSTRAINT PkSpeech_SpeechId PRIMARY KEY,
[UniqueName] [varchar](52) NOT NULL,
[NativeName] [nvarchar](52) NOT NULL,
[Place] [nvarchar](52) NOT NULL,
[Type] [smallint] NOT NULL,
[LanguageId] [char](2) NOT NULL CONSTRAINT FkSpeech_LanguageId FOREIGN KEY (LanguageId) REFERENCES Language(LanguageId) ON UPDATE CASCADE ON DELETE CASCADE,
[SpeakerId] [int] NOT NULL CONSTRAINT FkSpeech_SpeakerId FOREIGN KEY (SpeakerId) REFERENCES Speaker(SpeakerId) ON DELETE CASCADE,
[IsFavorite] [bit] NOT NULL,
[IsVisible] [bit] NOT NULL,
[CreatedDate] [datetime] NOT NULL DEFAULT GETDATE(),
[ModifiedDate] [datetime] NULL
)
Now I want to search the Table Speech
Sometimes by : SpeechId
Sometimes by : SpeakerId
Sometimes by : LanguageId
Sometimes by : SpeechId And LanguageId
Sometimes by : SpeakerId And LanguageId
All can have conditions with IsVisible, IsFavorite and Type columns.
for example
I need all Speeches with
any particular SpeakerId and LanguageId
with IsVisible equals to true
and IsFvaorite No Matter
and Type equals to Audio
For these type of queries I think the solution is
GO
CREATE PROCEDURE [dbo].[sprocGetSpeech]
@speechId int = NULL,
@uniqueName varchar(52) = NULL,
@nativeName nvarchar(52) = NULL,
@place nvarchar(52) = NULL,
@type smallint = NULL,
@languageId char(2) = NULL,
@speakerId int = NULL,
@isFavorite bit = NULL,
@isVisible bit = NULL
AS
SELECT
SpeechId,
UniqueName,
NativeName,
Place,
Type,
LanguageId,
SpeakerId,
IsFavorite,
IsVisible,
CreatedDate,
ModifiedDate
FROM
Speech
WHERE
SpeechId = @speechId
AND UniqueName = CASE WHEN @uniqueName IS NULL THEN [UniqueName] ELSE @uniqueName END
AND NativeName = CASE WHEN @nativeName IS NULL THEN [NativeName] ELSE @NativeName END
AND Place = CASE WHEN @place IS NULL THEN [Place] ELSE @place END
AND Type = CASE WHEN @type IS NULL THEN [Type] ELSE @type END
AND LanguageId = CASE WHEN @languageId IS NULL THEN [LanguageId] ELSE @languageId END
AND SpeakerId = CASE WHEN @speakerId IS NULL THEN [SpeakerId] ELSE @speakerId END
AND IsFavorite = CASE WHEN @isFavorite IS NULL THEN [IsFavorite] ELSE @isFavorite END
AND IsVisible = CASE WHEN @isVisible IS NULL THEN [IsVisible] ELSE @isVisible END
Can anyone tell me?
Is it right way to do?
Do you have any better solution?
If my solution is better then Is there any performance loss with that query?
|