簡體   English   中英

SQL Server 2008中根據多條select語句建表插入行

[英]Create table and insert rows based on multiple select statements in SQL Server 2008

我的情況是在登錄我的網站后,我想顯示有多少員工活躍,不活躍以及部門明智,拼貼明智的員工計數列表。

為此,我創建了一個過程來創建臨時表,如果它不存在則刪除表創建臨時表,之后我寫了一些 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.

使用 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
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM