CREATE FUNCTION [dbo].[CSAPP_GET_FREE_VEHICLES](
@von DATETIME = NULL,
@bis DATETIME = NULL,  
@station_übergabe VARCHAR(255) = '%',
@gruppe VARCHAR(255) = '%',	
@vorlaufzeit_unix Bigint = NULL,
@nachlaufzeit_unix Bigint = NULL,--   
@resNo BIGINT = NULL,
@mva VARCHAR(10)
)
RETURNS BIT
BEGIN
DECLARE @station VARCHAR(255)
DECLARE @gruppen_wert_temp VARCHAR(32)
DECLARE @gruppenindex BIGINT
DECLARE @gruppenanzahl BIGINT
DECLARE @kfzgruppe TABLE (GRUPPE VARCHAR(32))
DECLARE @freeMvaNumbers TABLE (mva varchar(10))
DECLARE @free BIT
SET @station = @station_übergabe
INSERT INTO @freeMvaNumbers 
			SELECT a.mvanummer
			FROM autos a,autoszusdaten z
			WHERE a.mvanummer=z.mvanummer 
			AND (a.inReparatur IS NULL OR a.inReparatur ='N')
			AND a.KFZGRUPPE = @gruppe
			AND (a.Standort IN (SELECT aval FROM dbo.GET_TABLE_FROM_LIST(@station)) OR @station = '%') 
			AND a.mvanummer IN (SELECT mvanr FROM aktive) 			
			AND  NOT EXISTS (
			SELECT * FROM dbo.MIETVERTRAEGE WHERE mvanummer = a.mvanummer AND
			
			(VERTRAGSNUMMER <> @resNo OR @resNo IS NULL) AND
			(NOT (dbo.VTR_GetStartDat(vertragsnummer) > DATEADD(SECOND, @vorlaufzeit_unix, @bis)) AND not(DATEADD(SECOND, @nachlaufzeit_unix, dbo.VTR_GetEndDat(vertragsnummer)) < @von)))
		
		IF @mva IN (SELECT * FROM @freeMvaNumbers)
			RETURN 1
		
		RETURN 0
END
