我想使用参数值作为查询的一部分,如下所示:
SELECT * FROM SOME_TABLE WHERE @PARAM
其中@PARAM =“ID = 1”
这甚至可能吗?
答案 0 :(得分:0)
是的,你只需要使用动态SQL:
http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
DECLARE @SQLQuery AS NVARCHAR(500)
SET @SQLQuery = 'SELECT * FROM table WHERE ' + @PARAMS
EXECUTE sp_executesql @SQLQuery
动态SQL有一些你应该注意的缺点,如果你想使用它,请阅读这篇文章了解更多细节:
答案 1 :(得分:0)
Declare @query Varchar(max)
Set @query = 'SELECT * FROM table WHERE ' + @parameter
exec(@query)
我不记得语法,但你可以做这样的事情。
答案 2 :(得分:0)
其他答案似乎或多或少是正确的,但这是一个完整的例子,您可以自己尝试:
/* We'll want two different variables--one
for the query as a whole, one for the
parameter.
*/
DECLARE @sSql VARCHAR(MAX),
@sParm VARCHAR(MAX);
----------------------------------------------------
/* Build a temp table for demonstration ... */
IF OBJECT_ID('tempdb..#table') IS NOT NULL BEGIN
DROP TABLE #table
END
CREATE TABLE #table (
[Id] INT IDENTITY PRIMARY KEY,
[Name] VARCHAR(100),
[Value] INT
)
INSERT INTO #table (Name, Value) VALUES ('Test1', 1)
INSERT INTO #table (Name, Value) VALUES ('Test2', 2)
----------------------------------------------------
/* Our complete query is some base plus the input
parameter
*/
SELECT @sParm = 'Id = 1';
SELECT @sSql =
'SELECT
t.[Name],
t.[Value]
FROM #table t WITH (NOLOCK)
WHERE ' + @sParm + ''
EXEC(@sSQL)