Sql-server – how to select first 9 numbers from other table from database using sql query

sql server

I want to fetch first 9 numbers from matching with other column please help me to find out thank you….?

SELECT MAINFILE.facno,GLMAST.fglhead   
FROM MAINFILE   
INNER JOIN GLMAST ON LEFT(MAINFILE.facno,9) like GLMAST.fglcode and GLMAST.fglhead='" & ComboBox2.Text & "' "

I am matching glcode='010000101' with facno='010000101000001' where i want to select first 9 numbers to match with glcode from facno…i hope my concept understood..

Best Answer

If I understand correctly your requirement, this should do the trick:

WITH MAINFILE (facno) AS (
    SELECT '010000101000001'
),
GLMAST (fglcode) AS (
    SELECT '010000101'
)
SELECT MAINFILE.facno --,GLMAST.fglhead   
FROM MAINFILE   
INNER JOIN GLMAST 
    ON MAINFILE.facno LIKE GLMAST.fglcode + '%'
    --and GLMAST.fglhead='" & ComboBox2.Text & "' "

Please note that the predicate on GLMAST.fglhead is prone to SQL injection. I strongly suggest to rewrite this code in a more secure way.