|
I have a stored procedure named "processInventory" like the following.
Depending on the passed in parameters, I would like to add a WHERE
clause for "select" action. For example, if any varchar type of
parameter is passed in, the where clause would use "LIKE" operator. For
example, "Select * from Main where [s/n] like @Serial. All other types
will use "=" operator. For example, "Select * from Main where MAKE =
@Make and Type = @type".
How could this be achieved? Thanks.
CREATE PROCEDURE processInventory
@Action varchar(7),
@ControlNumber int = null,
@AssetTag int = null,
@Serial varchar(50) = null,
@Description varchar(50) = null,
@Make int = null,
@Type int = null,
@Model int = null,
@Status int = null,
@Networked bit = null,
@LoginName varchar(50) = null,
@Shared bit = null,
@Org varchar(15) = null,
@RecordDate datetime = null,
@LastUpdate datetime = null,
@ManufactureDate datetime = null,
@Comment ntext = null
AS
declare @processError int
set @processError = 0
if @Action = 'Select' goto selectInventory
else
If @Action = 'Update'
begin
if @ControlNumber = null return(1) --Required parameter value not
specified
else
goto updateInventory
end
else
if @Action = 'Insert'
begin
if @Serial = null return(1) --Required parameter value not
specified
else
goto InsertInventory
end
else
if @Action = 'Delete'
begin
if @ControlNumber = null return(1) --Required parameter value
not specified
else goto deleteInventory
end
selectInventory:
if @Serial <> null
begin
select * from Main where [S/N] like @Serial
if @@Error<>0
begin
set @processError = @@Error
return @processError
end
end
else
if @ControlNumber <> null
begin
select * from Main where ControlNumber = @ControlNumber
if @@Error <>0
begin
set @processError = @@Error
return @processError
end
end
else
select top 100* from Main
updateInventory:
update MAIN
set [Org Asset Tag] = @AssetTag, [S/N] = @Serial, [Description]
= @Description, Make = @Make, Type = @Type,
Model = @Model, Status = @Status, Networked = @Networked,
LoginName = @LoginName, Shared = @Shared,
Org = @Org, [Date Of Record] = @RecordDate, [Date Last
Updated] = @LastUpdate, [Manuf Date] = @ManufactureDate,
Comments = @Comment
where ControlNumber = @ControlNumber
if @@ERROR <> 0
begin
set @processError = @@ERROR
return @processError
end
else
return(0) -- successful update
insertInventory:
insert MAIN([Org Asset Tag], [S/N], [Description], Make, Type,
Model, Status, Networked, LoginName, Shared,
Org, [Date Of Record], [Date Last Updated], [Manuf
Date],Comments)
values(@AssetTag, @Serial, @Description, @Make, @Type, @Model,
@Status, @Networked, @LoginName, @Shared,
@Org, @RecordDate, @LastUpdate, @ManufactureDate,
@Comment)
if @@ERROR <> 0
begin
set @processError = @@ERROR
return @processError
end
else return(0) -- successful insert
deleteInventory:
delete MAIN where ControlNumber = @ControlNumber
if @@ERROR <> 0
begin
set @processError = @@ERROR
return @processError
end
else return(0) -- successful delete
GO |