为查询string声明variables
嘿,所有,我想知道是否有办法在MS SQL Server 2005中做到这一点:
DECLARE @theDate varchar(60) SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59''' SELECT AdministratorCode, SUM(Total) as theTotal, SUM(WOD.Quantity) as theQty, AVG(Total) as avgTotal, (SELECT SUM(tblWOD.Amount) FROM tblWOD JOIN tblWO on tblWOD.OrderID = tblWO.ID WHERE tblWO.Approved = '1' AND tblWO.AdministratorCode = tblWO.AdministratorCode AND tblWO.OrderDate BETWEEN @theDate ) ... etc
可能做什么?
大卫
这是可能的,但它需要使用dynamicSQL。
我build议阅读dynamicSQL的诅咒和祝福,然后继续…
DECLARE @theDate varchar(60) SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59''' DECLARE @SQL VARCHAR(MAX) SET @SQL = 'SELECT AdministratorCode, SUM(Total) as theTotal, SUM(WOD.Quantity) as theQty, AVG(Total) as avgTotal, (SELECT SUM(tblWOD.Amount) FROM tblWOD JOIN tblWO on tblWOD.OrderID = tblWO.ID WHERE tblWO.Approved = ''1'' AND tblWO.AdministratorCode = tblWO.AdministratorCode AND tblWO.OrderDate BETWEEN '+ @theDate +')' EXEC(@SQL)
dynamicSQL只是一个SQL语句,在执行之前由一个string组成。 所以通常的string连接发生。 只要你想在SQL语法中做一些不允许的事情,就需要dynamicSQL,比如:
- 用于表示IN子句的逗号分隔值列表的单个参数
- 表示值和SQL语法的variables(IE:您提供的示例)
EXEC sp_executesql
允许你使用bind / preparedstatement参数,所以你不必关心转义SQL注入攻击的单引号/ etc。
DECLARE @theDate DATETIME SET @theDate = '2010-01-01'
然后改变你的查询来使用这个逻辑:
AND ( tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate) AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate) )
确实,这是不可能的。
您可以构build整个查询并将其作为string执行。
使用EXEC
您可以使用以下示例来构buildSQL语句。
DECLARE @sqlCommand varchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) SET @columnList = 'CustomerID, ContactName, City' SET @city = '''London''' SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city EXEC (@sqlCommand)
使用sp_executesql
通过使用这种方法,您可以确保传递到查询中的数据值是正确的数据types,并避免使用更多的引号。
DECLARE @sqlCommand nvarchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) SET @columnList = 'CustomerID, ContactName, City' SET @city = 'London' SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city' EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city
参考