如何在select查询中使用参数?

时间:2017-01-20 09:52:49

标签: sql sql-server sql-server-2008 select sql-server-2008-r2

我有桌子:

表名:tbl_Income

EmployeeID      Element      FinancialYear   Jan    Feb    Mar

00402060         Basic         2016-2017     100    200    300
00402060         HRA           2016-2017     100    200    300
00402060         DA            2016-2017     100    200    300

我想从tbl_Income中获取数据。

我在下面找到问题。

Declare @Month varchar(10) = 'Jan'

select @Month  from tbl_Income where  EmployeeID = '00402060' and Element = 'Basic' and  FinancialYear = '2016-2017' 

我想低于输出

OUTPUT : 

   Jan
1  100    

请帮帮我......

3 个答案:

答案 0 :(得分:2)

您可以像这样使用动态SQL:

declare @sql nvarchar(max)
Declare @Month varchar(10) = 'Jan'
declare @income int

set @sql = 'select @inc=' + @Month + ' from tbl_Income where  EmployeeID = ''00402060'' and Element = ''Basic'' and  FinancialYear = ''2016-2017'''

exec sp_executesql @sql, N'@inc int OUTPUT', @inc=@income OUTPUT
select @income as income

请注意,这对SQL注入攻击是开放的。

你最好修理你的设计。

答案 1 :(得分:1)

Declare @Month varchar(10) = 'Jan'
declare @v nvarchar(max)
declare @v1 INT
set @v =CONCAT('select @v1=' ,@month, ' from 
table_a where  EmployeeID = ''00402060'' and Element = ''Basic'' and  FinancialYear = ''2016-2017''') 
PRINT @V
EXECUTE sp_executesql @v,N'@V1 INT OUTPUT', @V1=@V1 OUTPUT;  
SELECT @V1;

答案 2 :(得分:0)

[样本数据库设计] [1]

[1]:https://i.stack.imgur.com/2vxEb.png - 表“dbo.Month”

    CREATE TABLE dbo.Month (
  Id int NOT NULL,
  Name nvarchar(50) NOT NULL,
  CONSTRAINT PK_Month PRIMARY KEY CLUSTERED (Id)
)

- 表IncomeType“

    CREATE TABLE dbo.IncomeType (
  Id int NOT NULL,
  Name nvarchar(50) NOT NULL,
  CONSTRAINT PK_IncomeType PRIMARY KEY CLUSTERED (Id)
)

- 表格“FinancialYear”

    CREATE TABLE dbo.FinancialYear (
  Id int NOT NULL,
  YearSpan nvarchar(50) NOT NULL,
  CONSTRAINT PK_FinancialYear PRIMARY KEY CLUSTERED (Id)
)

- 表格“员工”

   CREATE TABLE dbo.Employee (
  Id int NOT NULL,
  Name nvarchar(50) NOT NULL,
  CONSTRAINT PK_Employee PRIMARY KEY CLUSTERED (Id)
)

- 表“收入”

    CREATE TABLE dbo.Income (
  Id int NOT NULL,
  EmployeeId int NOT NULL,
  TypeId int NOT NULL,
  YearSpanId int NOT NULL,
  MonthId int NOT NULL,
  CONSTRAINT PK_Income PRIMARY KEY CLUSTERED (Id)
)

- 更改每个表以添加外键引用

ALTER TABLE Income
  ADD CONSTRAINT FK_Income_Employee FOREIGN KEY (EmployeeId) REFERENCES Employee (Id)

    ALTER TABLE dbo.Income
  ADD CONSTRAINT FK_Income_FinancialYear FOREIGN KEY (YearSpanId) REFERENCES dbo.FinancialYear (Id)


    ALTER TABLE dbo.Income
  ADD CONSTRAINT FK_Income_IncomeType FOREIGN KEY (TypeId) REFERENCES dbo.IncomeType (Id)

    ALTER TABLE dbo.Income
  ADD CONSTRAINT FK_Income_Month FOREIGN KEY (MonthId) REFERENCES dbo.Month (Id)
  1. EmployeeID将来自Employee表
  2. 元素将来自收入类型表
  3. 财务年度 - 来自财政年度表
  4. MonthId from the months table
  5. 现在,一个简单的连接可以帮助您使用外键引用

    获取每个值