Hi,
Yes, you can do this. Use the following code to create dynamic SQL in a procedure. I am writing a simple example for your reference.
------------------------------------------------------------------------
Create proc proc_Test
@param1 varchar(100), -- some parameter value
@param2 char(1), --use this as a condition, if this value is 'Y' then use @PARAM1 in the where clause else use @PARAM3 in the where clause.
@param3 varchar(100) ---some parameter value
As
begin
Declare @sql varchar(1000) ----Declare a string variable
set @sql = 'Select col1, col2, col3 from Test_table where 1=1 ' ---set the basic text in the @sql variable
if @param2='Y' ---Check the condition, if @param2 = 'Y' then
------- append the @sql variable using this format. Make sure you don't put the variable within single quotes, else it will take it as constant. To use the value of the variable, close the quotes and use + sign to append value. Use the same approach for @PARAM3
set @sql = @sql + ' and col1 = ' + @param1
else
set @sql = @sql + ' and col1 = ' + @param3
exec (@sql) ----Use this statement to execute the value of @SQL
print (@SQL) ----You can take a look at the contents of @SQL and ensure that your query is created dynamically and correctly with all values.
end
------------------------------------------------------------------------
Hope this will be helpful to you. If any doubt, let me know.
Thanks
Sudhir