简体   繁体   English

如何在SQL Server中参数化具有特殊字符的查询?

[英]How to parameterize query with special character in SQL Server?

I want to execute a query with concatenation of two columns so I have done this: 我想执行两列串联的查询,所以我做到了:

Select 
    Id, PtName + ' ('+Investigation+')' as PtName, Y, M, D, PtCode 
From 
    DiagMain

But when I am trying to parameterize this query, it's not working. 但是,当我尝试参数化此查询时,它不起作用。

Like this: 像这样:

declare @Query nvarchar(MAX)

set @Query = 'Select Id, PtName + ''( +''Investigation''+ )'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'
Exec(@Query)

What I am doing wrong here? 我在这里做错了什么?

Your single quotes were misplaced, they should surround the brackets ( & ) : 您的单引号放错了位置,应放在方括号()

set @Query = 'Select Id, PtName + ''('' +Investigation+ '')'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'

You could debug this by using the print command: 您可以使用print命令来调试它:

print @Query
DECLARE @Query NVARCHAR(MAX)
SET @Query ='Select  Id, PtName  + '' (''+Investigation+'')'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'
PRINT @Query
Exec(@Query)

If you need to execute above query then replace your Exec(@Query) with exec sp_executesql @Query because to run dynamic query your need to call sql inbuilt procedure. 如果您需要执行上述查询,请用exec sp_executesql @Query替换您的Exec(@Query) ,因为要运行动态查询,您需要调用sql内置过程。 So query you need to run would be following 因此,您需要运行的查询将如下

declare @Query nvarchar(MAX)    
set @Query = 'Select Id, PtName + ''( +''Investigation''+ )'' as PtName, Y, M, D, Sex, PtCode FROM DiagMain'
exec sp_executesql @Query

Happy Coding :-) 快乐编码:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM