Home > Database > Mysql Tutorial > How to Properly Parameterize Pass-Through Queries in T-SQL's Dynamic SQL?

How to Properly Parameterize Pass-Through Queries in T-SQL's Dynamic SQL?

Susan Sarandon
Release: 2025-01-03 07:01:45
Original
182 people have browsed it

How to Properly Parameterize Pass-Through Queries in T-SQL's Dynamic SQL?

Dynamic SQL in T-SQL: Paramaterized Pass-Through

In T-SQL, dynamic SQL can be a useful tool for constructing queries at runtime. However, it is important to understand how to handle parameters within dynamic SQL statements.

Consider the following dynamic query:

CREATE PROCEDURE [dbo].[sp_Test1] /* 'b0da56dc-fc73-4c0e-85f7-541e3e8f249d' */
(
  @p_CreatedBy UNIQUEIDENTIFIER
)
AS
DECLARE @sql NVARCHAR(4000)
SET @sql = '
DECLARE @p_CreatedBY UNIQUEIDENTIFIER

SELECT 
  DateTime,
  Subject,
  CreatedBy
FROM
(
  SELECT 
    DateTime, Subject, CreatedBy, 
    ROW_NUMBER() OVER(ORDER BY DateTime ) AS Indexing
  FROM
    ComposeMail
  WHERE 
    CreatedBy = @p_CreatedBy /* <--- the problem is in this condition */
) AS NewDataTable
';

EXEC sp_executesql @sql
Copy after login

This query attempts to select data from the ComposeMail table based on the @p_CreatedBy parameter. However, when executing this query with parameters, no results are returned.

To resolve this issue, it is crucial to pass the parameters to sp_executesql, as demonstrated in the following code:

...
WHERE 
    CreatedBy = @p
...

EXECUTE sp_executesql @sql, N'@p UNIQUEIDENTIFIER', @p = @p_CreatedBY
Copy after login

In this updated code, the @p parameter is defined as a UNIQUEIDENTIFIER type and its value is set to the @p_CreatedBY parameter. This ensures that the parameter is properly passed to the dynamic SQL statement.

By following this technique, you can effectively use parameters within dynamic SQL queries in T-SQL.

The above is the detailed content of How to Properly Parameterize Pass-Through Queries in T-SQL's Dynamic SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template