T-SQL:如何在动态SQL中使用参数?
我有以下动态查询,无需 WHERE
子句即可正常工作,该子句需要 UNIQUEIDENTIFIER
。
当我传递它时,我没有得到结果。 我尝试了 CAST
和 CONVERT
,但没有结果。 我可能做错了,有人可以帮忙吗?
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
I have the following dynamic query which is working fine without the WHERE
clause, which is expecting UNIQUEIDENTIFIER
.
When I pass it in, I don't get a result. I tried CAST
and CONVERT
, but no result. I might be doing it wrong, can anybody help?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定您的变量是否以字符串格式或二进制格式填充,但您可能需要在 where 子句中引用 uniqueidentifier。 如果您只选择 uniqueidentifier 字段,它会以字符串还是二进制形式返回?
I'm not sure if your variable is getting populated in string format or binary, but you may need to quote the uniqueidentifier in your where clause. If you just select the uniqueidentifier field, does it come back as string or binary?
您必须将参数传递给 sp_executesql。 有关详细信息,请参阅 MSDN< /a>.
You must pass in the parameters to sp_executesql. See MSDN for details.
多参数语法。 也许这会为某人节省额外的 Google 搜索次数:
Multiple parameter syntax. Maybe this will save someone an extra Google Search: