在SQL Server中使用存储过程执行动态SQL命令的真实优点和缺点是什么?
EXEC (@SQL)
Run Code Online (Sandbox Code Playgroud)
与
EXEC SP_EXECUTESQL @SQL
Run Code Online (Sandbox Code Playgroud)
?
我想知道为什么我不能像这样使用变量列名:
declare @a as varchar;
set @a='TEST'
select @a from x;
Run Code Online (Sandbox Code Playgroud)
谢谢
我需要一些SQL逻辑方面的帮助,而且我已经工作(并且研究)了2天,但没有成功.
我的目标是尝试将ASP页面中的变量传递给存储过程,该过程将该变量用作where子句中列名的条件.
例如(我的查询的简化版本):
@strDept nvarchar(10), @strUser nvarchar(30)
-- The asp page will pass f18 to @strDept & Ted Lee to strUser
-- f18 is the column name in my database that I need in the where.
select x, y, z from table1 where @strDept in (@strUser)
-- and this is the select statement, notice the where clause.
Run Code Online (Sandbox Code Playgroud)
存储过程确实执行,但它不返回任何值,我知道它将@strDept视为文字nvarchar而不是列名.
所以我想我的问题是,如何让SQL Server 2005将@sqlDept变量视为列名?
我的原始查询使用@WF_ID作为参数名称,并且可以毫无问题地执行.我很懒,WF_要输入很多,所以我将参数重命名为@ID,但现在执行时抛出了SQLException.确切的消息是"无效的列名'_Page'"
以下是查询的两个版本和相应的代码.正如您所看到的,唯一改变的是参数名称.
SQL_Connection.Open();
SQL_Command.Connection = SQL_Connection;
SqlParameter param = new SqlParameter("@WF_ID", SqlDbType.Int);
param.Value = WF_ID;
SQL_Command.Parameters.Add(param);
SQL_Command.CommandText = "SELECT COUNT(*) AS MyCount from members WHERE ID = @WF_ID";
int numRows = Convert.ToInt32(SQL_Command.ExecuteScalar().ToString());
SQL_Command.Parameters.Clear();
Run Code Online (Sandbox Code Playgroud)
版本2.0破碎版
SQL_Connection.Open();
SQL_Command.Connection = SQL_Connection;
SqlParameter param = new SqlParameter("@ID", SqlDbType.Int);
param.Value = WF_ID;
SQL_Command.Parameters.Add(param);
SQL_Command.CommandText = "SELECT COUNT(*) AS MyCount from members WHERE ID = @ID";
int numRows = Convert.ToInt32(SQL_Command.ExecuteScalar().ToString());
SQL_Command.Parameters.Clear();
Run Code Online (Sandbox Code Playgroud)
我的初步想法是参数名称不能与其中一个列名相同...但我找不到任何明确说明的内容.
看看这个StackOverflow主题,你似乎无法通过参数传递列名.我可以在SQL存储过程中将列名作为输入参数传递
我正在尝试编写一个存储过程,它采用两个参数来从客户表中检索一些数据。
下面是存储过程,它不检索任何数据,但是当我只需键入选择查询时,它就可以工作。
有人可以帮我看看问题出在哪里吗?
CREATE PROCEDURE [dbo].[RecordsByColumnSearch]
@field VARCHAR(50),
@search VARCHAR(50)
AS
SELECT *
FROM Customers
WHERE @field = @search
Run Code Online (Sandbox Code Playgroud)
像这样执行这个存储过程:
EXEC dbo.RecordsByColumnSearch @field = CustomerID, @search = ALFKI;
Run Code Online (Sandbox Code Playgroud)
不返回任何数据,而运行此查询时会:
SELECT *
FROM customers
WHERE CustomerID = 'ALFKI';
Run Code Online (Sandbox Code Playgroud)
先感谢您 !