I am executing a dynamic SQL query. where parameters are passed dynamically. I first wrote similar to following code.
DECLARE @Id nvarchar(max);
DECLARE @query nvarchar(max);
SET @Id ='RMH_108'
SET @query ='Select *
FROM [A06].[Syn_RMDemand]
WHERE RMHierarchyId =' + @Id
PRINT @query
EXEC(@query)
Then I wrote this.
DECLARE @Id nvarchar(max);
DECLARE @query nvarchar(max);
SET @Id ='RMH_108'
SET @query ='Select *
FROM [A06].[Syn_RMDemand]
WHERE RMHierarchyId = '''+@Id+''''
PRINT @query
EXEC(@query)
This time code successfully executed. Since parameter can be empty I need to convert that to null. I modified the code and wrote this
DECLARE @Id nvarchar(max);
DECLARE @query nvarchar(max);
SET @Id = ''
SET @Id = NULLIF(@Id,'')
-- COMMENTED SET @Id ='RMH_108'
SET @query ='Select * FROM [A06].[Syn_RMDemand]
WHERE RMHierarchyId = '''+@Id+''''
PRINT @query
EXEC(@query)
No errors. Query crashed.
Does anybody come up with this sort of problem ?
Executing dynamic SQL queries Dynamic SQL queries are those built at runtime based on one or more variable values. To execute those queries, we must concatenate them into one SQL statement and pass them as a parameter to the sp_executesql stored procedure.
Executing dynamic SQL using sp_executesql sp_executesql is an extended stored procedure that can be used to execute dynamic SQL statements in SQL Server. we need to pass the SQL statement and definition of the parameters used in the SQL statement and finally set the values to the parameters used in the query.
What are the three ways that Dynamic SQL can be executed? Writing a query with parameters. Using EXEC. Using sp_executesql.
Handling SQL NULL values with Functions ISNULL(): The ISNULL() function takes two parameters and it enables us to replace NULL values with a specified value. The expression parameter indicates the expression which we want to check NULL values.
You should use sp_executeSQL
and remove string concatenation like this. I am assuming that if NULL
is passed you want all the rows to be returned.
Query
DECLARE @Id nvarchar(max);
DECLARE @query nvarchar(max);
SET @Id ='RMH_108'SET @query ='Select *
FROM [A06].[Syn_RMDemand]
WHERE RMHierarchyId = @Id OR @ID IS NULL'
PRINT @query
EXEC sp_executeSQL @query,N'@Id NVARCHAR(MAX)',@Id
Try the following:
SET @query ='Select * FROM [A06].[Syn_RMDemand]'
IF @Id IS NOT NULL
SET @query = @query + ' WHERE RMHierarchyId = '''+@Id+''''
If the parameter comes from client you better do with parametrized query(see @ughai's answer) in order to exclude sql injection
possibility...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With