根据SQL Server 2008中的多个select语句创建表并插入行

时间:2012-04-06 06:44:51

标签: c# asp.net sql-server-2008

我的情况是在登录我的网站之后我想要显示有多少员工是活跃的,不活跃的&对于部门明智的,拼贴明智的员工名单。

为此,我创建了一个创建临时表的过程,如果它不存在,则drop table创建临时表,之后我写了一些SQL查询来获取员工数,部门有条件&然后我将记录插入表格。

然后我需要插入的行。现在我的问题是在执行SQL的过程中执行但是它没有创建&插入任何行,我不知道为什么会这样。如果有人知道这个问题的解决方案,请帮助我。

我的代码:

alter proc SP_TEMPRECORDFORCOUNT
as
begin

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'TEMPRECORDFORCOUNT'))
BEGIN
   drop table dbo.TEMPRECORDFORCOUNT
END

create table dbo.TEMPRECORDFORCOUNT(totalemployeecount int,activeemployeecount int,inactiveemployeecount int,deptwiseemployeecount int,activeemployeecount int)

declare @totalemployeecount int
declare @activeemployeecount int
declare @inactiveemployeecount int
declare @deptwiseemployeecount int
declare @activeemployeecount int

select @totalemployeecount =COUNT(*) from Employee
select @activeemployeecount =COUNT(*) from Employee where status=1
select @inactiveemployeecount =COUNT(*) from Employee where status=0
select @deptwiseemployeecount = count(*) from Department where e_id !=null 
select @activeemployeecount = count(*) from Department d inner join Employee e on d.e_id =e.e_id where status_id=1

insert into TEMPRECORDFORCOUNT
(
totalemployeecount 
,activeemployeecount 
,inactiveemployeecount 
,deptwiseemployeecount 
,activeemployeecount 
)
values
(
@totalemployeecount ,
@activeemployeecount ,
@inactiveemployeecount ,
@deptwiseemployeecount ,
@activeemployeecount ,
)
end

is it correct way thing i'm doing? if not please correct me.

1 个答案:

答案 0 :(得分:0)

使用SQL Server 2008 R2,您可以选择表变量。

因此,您的陈述应更改为以下内容:

DECLARE @TEMPRECORDFORCOUNT TABLE(totalemployeecount int,activeemployeecount int,inactiveemployeecount int,deptwiseemployeecount int,activeemployeecount int)

insert into @TEMPRECORDFORCOUNT
(
totalemployeecount 
,activeemployeecount 
,inactiveemployeecount 
,deptwiseemployeecount 
,activeemployeecount 
)
values
(
@totalemployeecount ,
@activeemployeecount ,
@inactiveemployeecount ,
@deptwiseemployeecount ,
@activeemployeecount ,
)

SELECT * FROM @TEMPRECORDFORCOUNT
;