如何在sql server中的局部变量中存储多个查询值 [英] How to store multiple value of query in local variable in sql server

查看:625
本文介绍了如何在sql server中的局部变量中存储多个查询值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个字段值存储在局部变量中,并将该变量用于其他查询的where条件。

例如

I need to store a field value in local variable and that variable I want to use with where condition of other query.
for example

Declare @localVariable bigint
select distinct EmployeeCode from EmployeeMaster---this value i want store in local variable





和其他选择查询我想用这个变量例如





and other select Query i want use this variable for example

select EmployeeSalary,EmployeeName ,BranchCode,BranchName from EmployeeMaster EM inner join BranchMaster BM on Em.BranchCode=BM.BranchCode where EmployeeCode in (@localVariable)





我怎么能请任何人帮助我。



How can I do please anyone help me.

推荐答案

Declare @localVariable bigint

SELECT @localVariable = COALESCE(@localVariable  + ', ', '') +
   CAST(EmployeeCode AS varchar(5))
FROM EmployeeMaster

EXEC SP_EXECUTESQL 'select EmployeeSalary,EmployeeName ,BranchCode,BranchName
from EmployeeMaster EM inner join BranchMaster BM on Em.BranchCode=BM.BranchCode
where EmployeeCode in (' + @localVariable + ')'


亲爱的朋友

我认为你可以轻松使用

查询就像这样

Dear Friend
I think you can easly use in
The query becomes like this
select EmployeeSalary,EmployeeName ,BranchCode,BranchName from EmployeeMaster EM inner join BranchMaster BM on Em.BranchCode=BM.BranchCode where EmployeeCode in (select distinct EmployeeCode from EmployeeMaster )





如果你需要一个变量本身那么您可以在sqlserver中使用 #table或table variable 来获得所需的解决方案



Hooe你有解决问题的方法



问候

VKMallaya



If you need a variable itself then you can use #table or table variable in sqlserver for attaining the desired solution

Hooe you got solution to your problem

Regards
VKMallaya


这篇关于如何在sql server中的局部变量中存储多个查询值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆