简体   繁体   中英

Compare if 2 input numbers are in range of 2 columns

I have the ff table.

Series

startno | endno
1       | 99

and 2 inputs

DECLARE @inputstart int = 2, @inputend int = 100

I want to select where my 2 inputs lies in range of the ones in the table.

Try this.

SELECT * 
FROM Your_Table 
WHERE (StartNo BETWEEN @inputstart AND @inputend) OR (endno BETWEEN @inputstart AND @inputend)

If you want in which column lies between your inputs, then try it.

SELECT MAX(CASE WHEN StartNo BETWEEN @inputstart AND @inputend THEN StartNo 
                WHEN endno BETWEEN @inputstart AND @inputend THEN endno END)
FROM Your_Table 

try this

declare @inputstart int = 2, @inputend int = 100;

with cte as (
select 1 as startno, 99 as endno
) select * from cte where @inputstart between startno and endno
    and @inputend between startno and endno

Suppose We have Created a temp Table

CREATE TABLE #DeleteMe(startNo INT , endNo INT )

then we are inserting all the records in temp table For eg 1 to 100

;WITH nums AS
   (SELECT 1 AS startNo,1 AS endNo  
    UNION ALL
    SELECT startNo + 1 AS startNo,endNo + 1 AS endNo
    FROM nums
    WHERE nums.startNo <= 99)

INSERT INTO #DeleteMe
SELECT *
FROM nums  

/* Here is Start Main Part that you want.... */

DECLARE @inputstart as  int ,@inputend AS INT
SET @inputstart= 2 
SET  @inputend = 50

SELECT * FROM #DeleteMe WHERE 
convert(INT,startNo)   BETWEEN Convert(INT,CASE WHEN isnull(@inputstart,'')='' THEN startNo ELSE isnull(@inputstart,'') END)                     
AND Convert(INT, CASE WHEN isnull(@inputend,'')='' THEN endNo ELSE isnull(@inputend,'') END)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM