2
Answers

Sql Query for Table based on start and end character

manoj singh

manoj singh

7y
189
1
 Book ID  Name  Autor
 1  ABC  Manoj
 2  BBC  mnoj

 Self id  Start character  end car
 1  A  C
 2  D  I
 
I have two table Now I want record from first table with Selfid ( second table contains Starting character and End character like in above table all book Started with A,B,C comes with self id 1)
Answers (2)
2
Nitin Sontakke

Nitin Sontakke

NA 11.7k 2.2k 7y
Here you go...
 
  1. declare @books table  
  2. (  
  3.    [book_id] [integernot null  
  4.   ,[name]   [varchar](100) not null  
  5.   ,[author] [varchar](100) not null  
  6. )  
  7.   
  8. insert into @books values  
  9.  (1, 'ABC''Manoj')  
  10. ,(2, 'EAC''Kiran')  
  11. ,(3, 'BCd''Ravi')  
  12. ,(4, 'HCx''Rahul')  
  13. ,(5, 'JBC''Deepak')  
  14.   
  15. declare @shelf table  
  16. (  
  17.    [shelf_id]   [integernot null  
  18.   ,[char_from]  [char](1) not null  
  19.   ,[char_to]    [char](1) not null  
  20. )  
  21.   
  22. insert into @shelf values  
  23.  (1, 'A''C')  
  24. ,(2, 'D''F')  
  25. ,(3, 'G''I')  
  26. ,(4, 'J''L')  
  27.   
  28. select *  
  29. from @books b  
  30. left outer join @shelf s on ascii(substring(b.[name], 1, 1)) between ascii(s.[char_from]) and ascii(s.[char_to])  
For better performance, you can keep integer columns in shelf table and have it indexed and also an integer column having ascii value of first letter in books table and have it index and use those columns in the query.
 
Accepted
1
Dharmraj Thakur

Dharmraj Thakur

NA 4.1k 61.7k 7y
Hellow Manoj,
 
You can make multiple condition left join in this situation...
 
  1. create table Books  
  2. (  
  3. BookID int primary key identity(1,1),  
  4. Name varchar(max),  
  5. Autor varchar(max)  
  6. )  
  7. create table Chars  
  8. (  
  9. SelfID int primary key identity(1,1),  
  10. StartCharacter varchar(1),  
  11. EndCharacter varchar(1)  
  12. )  
  13.   
  14. insert into Books(Name,Autor) values ('ABC','Manoj')  
  15. insert into Books(Name,Autor) values ('BBC','mnoj')  
  16. insert into Chars(StartCharacter,EndCharacter) values ('A','C')  
  17. insert into Chars(StartCharacter,EndCharacter) values ('D','I')  
  18.   
  19. select bk.*, ch.SelfID   
  20. from Books bk  
  21. left join Chars ch   
  22. on ch.StartCharacter = SUBSTRING(bk.Name, 1, 1) and   
  23. ch.EndCharacter = SUBSTRING(bk.Name, LEN(bk.Name), 1)  
 
Next Recommended Forum