Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在sql中声明并连接变量_Sql_Sql Server_Stored Procedures - Fatal编程技术网

在sql中声明并连接变量

在sql中声明并连接变量,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,所以我想把几个值传递给一个存储过程。然后基于这些值,添加到一个变量中,该变量将被设置为my where子句。但我被难住了,谷歌也帮不了忙。这是我的想法 CREATE PROCEDURE sp_RunReport @TransType varchar(255), @Accounts varchar(75) AS --declare a varchar WHERE clause variable here IF @TransType <> '' --add to WHERE clau

所以我想把几个值传递给一个存储过程。然后基于这些值,添加到一个变量中,该变量将被设置为my where子句。但我被难住了,谷歌也帮不了忙。这是我的想法

CREATE PROCEDURE sp_RunReport @TransType varchar(255), @Accounts varchar(75)
AS

--declare a varchar WHERE clause variable here

IF @TransType <> ''
--add to WHERE clause variable

iF @Accounts <>''
--add to WHERE clause variable

SELECT * 
    FROM log
WHERE --my WHERE clause
创建过程sp_RunReport@TransType varchar(255),@Accounts varchar(75)
作为
--在此处声明varchar WHERE子句变量
如果@TransType“”
--添加到WHERE子句变量
如果@Accounts“
--添加到WHERE子句变量
选择*
从日志
WHERE——我的WHERE子句


我不明白这怎么可能。我可以用c语言在前端完成这一切,但我觉得这应该在存储过程中完成。非常感谢您的帮助

您可以使用
EXEC
使用动态SQL:

CREATE PROCEDURE sp_RunReport @TransType varchar(255), @Accounts varchar(75)
AS

DECLARE @where VARCHAR(4000) = ' WHERE 1=1'
DECLARE @sql NVARCHAR(4000)

IF @TransType <> ''
    SET @where = @where + ' AND TransType = ''' + @TransType + ''''

IF @Accounts <>''
    SET @where = @where + ' AND Accounts = ''' + @Accounts + ''''

SET @sql = 'SELECT * 
    FROM log' + @where

exec (@sql)

虽然前面的答案中的动态SQL可能不错,但我建议使用这种“纯”SQL方法

WHERE TransType = ISNULL(@TransType, TransType)
    AND Accounts = ISNULL(@Accounts, Accounts)
通过去掉ISULL(在WHERE子句中使用时不是最优的),可以优化性能,但这应该会给您一些想法


当然,除了
之外,您的逻辑可能会重新生成一个
,您还需要确保参数“正确地”为空(在我的情况下为NULL,或者如果您重新编写此函数以删除ISNULL,则会构成“空”)

请参阅exec\u sql:我想我只是错过了这个选项。
WHERE TransType = ISNULL(@TransType, TransType)
    AND Accounts = ISNULL(@Accounts, Accounts)