How the Dynamic SQL Works ?
set @sSQL='Insert into #tempBusDetails(Bus_Route_ID ,Bus_Route_Name ,Vehicle_No,Max_Occupacy,
Current_Occupacy ,Driver_Name ,Driver_Mobile_No ,Assistant_Name ,Assistant_Mobile_No,Hub_ID,HTML_StopName)
SELECT distinct(bd.Bus_Route_ID),bd.Bus_Route_Name, bd.Vehicle_No, bd.Max_Occupacy, dbo.Current_Count(bd.Bus_Route_ID) AS User_Count, bd.Driver_Name,
bd.Driver_Mobile_No,bd.Assistant_Name, bd.Assistant_Mobile_No, f.Facility_Name, dbo.fnc_CreateHTML_StopName(bd.Bus_Route_ID) AS HTML_StopName
FROM dbo.tbl_Bus_Details AS bd
INNER JOIN dbo.tbl_Facility AS f ON bd.Hub_ID = f.Facility_ID
INNER JOIN dbo.tbl_stop_details as sd on sd.Bus_route_id=bd.bus_route_id
WHERE bd.Inactive='+cast(@Inactive as varchar)+ ''
We have the doubt in the quotation mark(in the last line).
--> WHERE bd.Inactive='+cast(@Inactive as varchar)+ ''
-->is it like bd.Inactive=' (This quotation is end of start quote). If yes then why do we need the last two quotes(+ '').
-->or is it like this is wrapped in single quotes : '+cast(@Inactive as varchar)+ '. And the final quotation is closed for start quote.
Kindly guide me.
Answer : It like this is wrapped in single quotes : '+cast(@Inactive as varchar)+ '. And the final quotation is closed for start quote.
=====================================================================================
Question 2:
Example1:
declare @var varchar(max)
set @var='select * from tbl_user_master where first_name like'+ '''%anurag%'''
print @var
exec (@var)
--We get the result
Example2:
declare @var varchar(max)
set @var='select * from tbl_user_master where first_name like '''%anurag%''' '
print @var
exec (@var)
--Error
what is the difference between example1 and example2?
Answer
<<<First Example >>>
like' + '''%anurag%'''
^ ^^^ ^^^---- Close second string
| ||| ||----- 2nd character of a pair of quotes\
| ||| | - These create a single ' character
| ||| |------ 1st character of a pair of quotes/
| |||--------------- 2nd character of a pair of quotes\
| || - These create a single ' character
| ||---------------- 1st character of a pair of quotes/
| |----------------- Open second string
|--------------------- Close first string
<<<Second Example>>>
like '''%anurag%''' '
||| ||| |----- Or this...
||| |||------- Or this...
||| ||-------- Or this...
||| |--------- SQL not going to look at this...
||| ERK! SQL NO UNDERSTAND! **REDO FROM START** ***OUT OF CHEESE ERROR***
|||------------------ End of first string
||------------------- 2nd character of a pair of quotes\
| - These create a single ' character
|-------------------- 1st character of a pair of quotes/
Hope you liked it :) Happy coding. If this has helped you, kindly feel free to comment.
No comments:
Post a Comment