我在RAW sql中声明了两个变量
DECLARE @str nvarchar(max), @str1 nvarchar (max);
SET @str = " AND (c.BondSales_Confirmed <> -1)";
SET @str1 = " AND (c.BondSales_IssueType = 'REGULAR')";
我的SQL查询是:
SELECT * From t_BondSales Where (BondSales_cType <> 'Institute') " + str1 + str "
这里我收到以下错误:
错误:SQL问题:“+ str1 + str”
附近的语法不正确
任何人都可以帮我解释一下如何在where子句中连接String的正确语法吗?
答案 0 :(得分:10)
试试这个 -
DECLARE
@str NVARCHAR(MAX)
, @str1 NVARCHAR (MAX);
SELECT
@str = ' AND c.BondSales_Confirmed != -1'
, @str1 = ' AND c.BondSales_IssueType = ''REGULAR''';
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT *
FROM t_BondSales
WHERE BondSales_cType != ''Institute'''
+ @str
+ @str1
PRINT @SQL
EXEC sys.sp_executesql @SQL
答案 1 :(得分:9)
SELECT * FROM tbl_person WHERE CONCAT(first_name,' ',last_name) = 'Walter White';
但这确实不在mysql中工作:
SELECT * FROM tbl_person WHERE first_name+' '+last_name = 'Walter White';
答案 2 :(得分:1)
将列名称与值一起传递受SQL注入。请务必阅读这篇文章www.sommarskog.se/dynamic_sql.html
所以我建议你改变这样的代码
declare @BondSales_Confirmed int
declare @BondSales_IssueType varchar(100)
SELECT * From t_BondSales Where (BondSales_cType <> 'Institute')
AND (c.BondSales_Confirmed <> @BondSales_Confirmed or @BondSales_Confirmed is null)
AND (c.BondSales_IssueType = @BondSales_IssueType or @BondSales_IssueType is null)
如果您不想将条件应用于列BondSales_Confirmed和BondSales_IssueType
,则只传递null值