IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_SensorInUse]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[sp_SensorInUse] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_SensorInUse]') AND type in (N'P', N'PC')) BEGIN EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_SensorInUse] AS' END GO ALTER PROCEDURE [dbo].[sp_SensorInUse] @SensorSerialNumber nvarchar(50) = null AS BEGIN SET NOCOUNT ON; declare @SensorId int set @SensorId = [dbo].[foo_IdGetSensor](@SensorSerialNumber) select distinct z.Name as [Name] from (select ts.TestSetupName as Name from TestObjectSensors s inner join TestSetupObjects t ON s.TestObjectId = t.TestObjectId inner join TestSetups ts ON ts.TestSetupId = t.TestSetupId where s.SensorId = @SensorId union select ChannelId as Name from TestObjectChannelSettings tchs where tchs.SensorId = @SensorId ) z END GO