'Whether we should use static or dynamic SQL statements does NOT relate to an IF statement.
When choosing between static / dynamic SQL statements, you are suggested to use static SQL statements (usp_ListWorkOrder02) for most of the cases. Dynamic SQL statements are usually used when static SQL statements cannot fulfill your needs. Thus, use dynamic SQL statements (usp_ListWorkOrder01) only when you do NOT know the table names or the column names for a particular statement, or when the selection conditions (WHERE) is too complicated to be handled in a static way. (while there are still alternatives / workarounds for not using dynamic SQL statements.)' - http://social.microsoft.com/Forums/zh-HK/sqlserverzhcht/thread/012e75f8-1b92-4d2a-892a-915fe45b1e41
Question 1 : Use static or dynamic sql query ?
- Mostly use static
- Use dynamic sql query at below two cases
- Not know the table names
- Not know the column names
Question 2 : Use execute or sp_executesql when we are using dynamic sql query?
- different between execute and sp_executesql
- sp_executesql has input & output
- sp_executesql can pass parameter - avoid sql injection
- sp_executesql can cached execute plan
- Mostly use sp_executesql