SQL 2012 :: How Many Records Can Insert Into A Temp Table

Mar 25, 2014

I use code below to insert data into a temp table.

How many records can insert into a temp table?

Select * into #temp from ORDER

View 3 Replies


ADVERTISEMENT

SQL 2012 :: 1.5 Million Records Into Temp Table

Sep 23, 2014

I come from a web based world were loading 1.5 million records into a temp table is suicide. I’m doing more data warehouse stuff now and I was looking into optimizing a buddies proc and noticed he was loading 1.5 million records into a temp table. We had a discussion about it because being from a web world I was drastically against it. He on the other hand didn’t feel it was an issue being it gets called once maybe twice a day. The tempdb is set to autogrow and it is on a different drive than all the other databases on the box. It has one ldf and mdf. He’s creating an index on the table after load. Why we shouldn’t be loading 1.5 million recs into temp table?

View 5 Replies View Related

SQL 2012 :: Snapshot Getting Corrupted After Insert Update Few Million Records Into A Table

Mar 12, 2015

We are facing a weird scenario in which the snapshot is getting corrupted after insertupdate few million records in to a table .

SQL Server 2012
windows server 2008 R2
service pack 1
64-bit OS

View 1 Replies View Related

SQL Server 2012 :: How To Quickly Update / Insert 3M Records In Large Table

Mar 28, 2015

Our system runs a SQL Server 2012 DB, it has a table (table_a) which has over 10M records. Our system have to receive data file from previous system daily which contains approximate 3M updated or new records for table_a. My job is to update table_a with the new data.

The initial solution is:

1 Create a table (table_b) which structur is as the same as table_a

2 Use BCP to import updated records into table_b

3 Remove outdated data in table_a:
delete from table_a inner join table_b on table_a.key_fileds = table_b.key_fields

4 Append updated or new data into table_a:
insert into table_a select * from table_b

As the test result, this solution is very inefficient. Step 3 costs several hours, e.g. How can I improve it?

View 9 Replies View Related

SQL Server 2012 :: Set Based Method To Insert Missing Records Into Table - Right Join Not Work

Apr 24, 2014

I have table A (EmployeeNumber, Grouping, Stages)
and
Table B (Grouping, Stages)

Table A could look like the following where the multiple employees could have multiple types and multiple stages.

EmployeeNumber, Type, Stages
100, 1, Stage1
100, 1, Stage2
100, 2, Stage1
100, 2, Stage2
200, 1, Stage1
200, 2, Stage2

Table B is a list of requirements that each employee must have. So every employee must have a type 1 and 2 and the associated stages listed below.

Type, Stage
1, Stage1
1, Stage2
2, Stage1
2, Stage2
2, Stage3
2, Stage4

So I know that each employee should have 2 Type 1's and 4 Type 2's. I hope that makes sense, I'm trying to change my data because ours is very proprietary.

I need to identify employees who do not have all their stages and list the stages they are missing. The final report should only have employees and the associated missing types and stages.

I do a count by employee to see how many types they have to identify the ones that don't have all the types and stages.

My count would look something like this:

EmployeeNumber Type Total
100, 1, 2
100, 2, 2
200, 1, 1
200 1, 2

So I know that employee 100 should have 2 more Type 2's and employee 200 should have 1 more Type 1 and 2 more Type 2's based on the required list.

The problem I'm having is taking that required list and joining to my list of employees with missing data and pulling from it the types and stages that are missing by employee. I thought I could get a list of the employees that are missing information and right join it to the required list where the missing records would be nulls. But, that doesn't work because some employees do have the required information and so I'm not getting any nulls returned.

View 9 Replies View Related

Unable To Get Records From Temp Table Using ASP

Nov 23, 2004

PLease help me with a intruiging problem with Stored Procedure, which is driving me mad.......

I wrote a Stored Procedure as listed below.
I've included the options
SET NOCOUNT ON
SET QUOTED_IDENTIFIER OFF

the results are stored in a #Temp table

The SP executes fine on Query Analyzer, and shows the contents of the temp table. BUt when I run this SP using ASP, I got the following error
-----------
ADODB.Recordset (0x800A0E78)
Operation is not allowed when the object is closed.
/test_site/test.asp, line 59
------------

I've tried using Recordset.MoveNextRecordset, if at all there are more than one recordset, obviously I got the same error







CREATE PROCEDURE atul_med.[sp_rep_sale2]
(
@rep_in varchar(100)

)
AS
SET NOCOUNT ON
SET QUOTED_IDENTIFIER OFF

DECLARE
@REP int,
@temp_pack varchar(20),
@temp_ntp int,
@temp_party_code varchar(20),
@temp_party_name varchar(20),
@temp_prod_code varchar(20),
@temp_prod_desc varchar(20),
@tot_qty int,
@tot_amount int,
@iCnt int,
@tot_sale_qty int,
@net_tot_sale_qty int,
@TableName varchar(10)

select @REP= @rep_in
set @tot_sale_qty=0
set @net_tot_sale_qty=0
set @TableName='#Test2'
--select @TableName='Test'
set @page=1
set @RecsPerPage=100

Declare @SQL VarChar(1000),
@cnt int,
@iCurLine int, @SQLX VarChar(1000)


set @iCurLine=1


set @iCurLine=1

select @Cnt = (SELECT count(*) FROM VW_PART_REP WHERE (REP = @REP))
print "Nos Of Party :"+ convert(char(1),@iCnt)

Create Table #Test2 (ID int identity,prod_desc nvarchar(100),pack nvarchar(100),ntp int)-- ,tot_qty int ,tot_amt int )




while @iCurLine <= @cnt
begin
SELECT @SQL= "ALTER TABLE #Test2 ADD "
SELECT @SQL = @SQL + "party_qty"+convert(char(2),@iCurLine)+" int "
set @iCurLine=@iCurLine+1
Exec (@SQL)
print @sql
end
SELECT @SQL= "ALTER TABLE #Test2 ADD "
SELECT @SQL = @SQL +"tot_qty int , tot_amt int "
SELECT @SQL = @SQL
exec (@SQL)
print @SQL



select * from #Test2

--Create Table #Test1 (ID int identity,prod_desc nvarchar(100),pack nvarchar(100),ntp int,party_qty1 int ,party_qty2 int ,party_qty3 int ,party_qty4 int ,party_qty5 int ,tot_qty int ,tot_amt int )
set @iCurLine=1


--=============================================



--print '=================Product Name========================'
DECLARE PROD_CUR CURSOR FOR
SELECT distinct(prod_code) as prod_code,prod_desc,pack,ntp FROM VW_sales_sum
WHERE (REP = @REP)
group by prod_code,prod_desc,pack,ntp

Declare @SQL_ins VarChar(1000)

OPEN PROD_CUR
FETCH NEXT FROM PROD_CUR
INTO @temp_prod_code,@temp_prod_desc,@temp_pack,@temp_n tp

WHILE @@FETCH_STATUS = 0
BEGIN


--Print @temp_prod_desc+'-'+convert(varchar(10),@temp_pack)+'-'+convert(varchar(10),@temp_ntp)
--print '=================prod_code :'+convert(varchar(10),@temp_prod_code)+'========= ==============='
print "============Insert Statement============"

SET @SQL_ins = "Insert into "+@TableName+" values("
SET @SQL_ins = @SQL_ins +""""+ @temp_prod_desc+""","""+@temp_pack+""","""+convert(char(10),@temp_ntp)+""","


DECLARE Party_CUR1 CURSOR FOR
SELECT party_code,party_name FROM VW_PART_REP
WHERE (REP = @REP) group by party_code,party_name

DECLARE @SQL1 varchar(10),@SQL2 varchar(100)
set @SQL2=''
OPEN Party_CUR1
FETCH NEXT FROM Party_CUR1
INTO @temp_party_code,@temp_party_name



WHILE @@FETCH_STATUS = 0
BEGIN
print "==Party_name :"+ @temp_party_name +"===Party_Code :"+convert(char(3),@temp_party_Code)
set @tot_sale_qty=0
set @tot_sale_qty= (select sum(issuedqty)as tot_qty from vw_sales_sum
where party_code =@temp_party_code
and (REP = @REP)
and (prod_code=@temp_prod_code))
if @tot_sale_qty IS NULL
begin
set @tot_sale_qty=0
print "===Tot Qty :"+convert(varchar(10),@tot_sale_qty)
end
else
begin
print "===Tot Qty :"+convert(varchar(10),@tot_sale_qty)
end
SELECT @SQL1 = @tot_sale_qty
select@net_tot_sale_qty=@net_tot_sale_qty+@tot_sale_qty
--print @SQL1
Select @SQL2 = @SQL2 + @SQL1 +","



FETCH NEXT FROM Party_CUR1
INTO @temp_party_code,@temp_party_name

END

CLOSE Party_CUR1
DEALLOCATE Party_CUR1
print '==============================='
print @SQL2+convert(char(4),@net_tot_sale_qty)


--set @net_tot_sale_qty=@tot_sale_qty+@net_tot_sale_qty
--SET @SQL = @SQL+convert(char(10),@tot_sale_qty)+','
--set @tot_sale_qty=0

Select @SQL_ins = @SQL_ins+@SQL2+convert(char(8),@net_tot_sale_qty)
Select @SQL_ins = @SQL_ins+","
Select @SQL_ins = @SQL_ins+convert(char(12),(@net_tot_sale_qty*@temp _ntp))
Select @SQL_ins = @SQL_ins+")"
print @SQL_ins
Exec (@SQL_ins)

select@net_tot_sale_qty=0
FETCH NEXT FROM PROD_CUR
INTO @temp_prod_code,@temp_prod_desc,@temp_pack,@temp_n tp


END


CLOSE PROD_CUR

DEALLOCATE PROD_CUR



SELECT * FROM #Test2


SET NOCOUNT OFF
GO
SET QUOTED_IDENTIFIER ON
GO

View 8 Replies View Related

Create Temp Table/loop Through Records

Jun 19, 2008

Hi all

I'm new to sql and could do with some help resolving this issue.

My problem is as follows,

I have two tables a BomHeaders table and a BomComponents table which consists of all the components of the boms in the BomHeaders table.

The structure of BOMs means that BOMs reference BOMs within themselves and can potentially go down many levels:

In a simple form it would look like this:

LevelRef: BomA

1component A
1component B
1Bom D
1component C


What i would like to do is potentially create a temporary table which uses the BomReference as a parameter and will loop through the records and bring me back every component from every level

Which would in its simplest form look something like this

LevelRef: BomA

1......component A
1......component B
1......Bom D
2.........Component A
2.........Component C
2.........Bom C
3............Component F
3............Component Z
1......component C

I would like to report against this table on a regular basis for specific BomReferences and although I know some basic SQL this is a little more than at this point in time i'm capable of so any help or advice on the best method of tackling this problem would be greatly appreciated.

also i've created a bit of a diagram just in case my ideas weren't conveyed accurately.


Bill Shankley

View 4 Replies View Related

SQL Server 2012 :: Stored Procedures Compiles Even When There Is No CREATE TABLE For A Temp Table

Feb 11, 2015

i am inserting something into the temp table even without creating it before. But this does not give any compilation error. Only when I want to execute the stored procedure I get the error message that there is an invalid temp table. Should this not result in a compilation error rather during the execution time.?

--create the procedure and insert into the temp table without creating it.
--no compilation error.
CREATE PROC testTemp
AS
BEGIN
INSERT INTO #tmp(dt)
SELECT GETDATE()
END

only on calling the proc does this give an execution error

View 3 Replies View Related

SP5a - Cusor Skipping Records On Temp Table

Dec 14, 1999

Hello,
Just in case anybody has had this problem after applying service pack 5a.
a stored procedure that sets serial numbers on records on a temporary table is skipping every other record.
I ran the code manually on isql and could not replicate the error, however when re-compiled on stored procedure it fails misserably.
when is Microsoft going to release a service pack that actually works?

Did you know that Executive does not recognize 2000 as a leap year?

If anybody has any suggestions on this problem, besides the obvious (using a real table) please write back
thanks.

David E. Pierri
Pseudo data-admin
ACNY

View 1 Replies View Related

INSERT INTO - Data Is Not Inserted - Using #temp Table To Populate Actual Table

Jul 20, 2005

Hi thereApplication : Access v2K/SQL 2KJest : Using sproc to append records into SQL tableJest sproc :1.Can have more than 1 record - so using ';' to separate each linefrom each other.2.Example of data'HARLEY.I',03004,'A000-AA00',2003-08-29,0,0,7.5,7.5,7.5,7.5,7.0,'Notes','General',1,2,3 ;'HARLEY.I',03004,'A000-AA00',2003-08-29,0,0,7.5,7.5,7.5,7.5,7.0,'Notes','General',1,2,3 ;3.Problem - gets to lineBEGIN TRAN <---------- skipsrestINSERT INTO timesheet.dbo.table14.Checked permissions for table + sproc - okWhat am I doing wrong ?Any comments most helpful......CREATE PROCEDURE [dbo].[procTimesheetInsert_Testing](@TimesheetDetails varchar(5000) = NULL,@RetCode int = NULL OUTPUT,@RetMsg varchar(100) = NULL OUTPUT,@TimesheetID int = NULL OUTPUT)WITH RECOMPILEASSET NOCOUNT ONDECLARE @SQLBase varchar(8000), @SQLBase1 varchar(8000)DECLARE @SQLComplete varchar(8000) ,@SQLComplete1 varchar(8000)DECLARE @TimesheetCount int, @TimesheetCount1 intDECLARE @TS_LastEdit smalldatetimeDECLARE @Last_Editby smalldatetimeDECLARE @User_Confirm bitDECLARE @User_Confirm_Date smalldatetimeDECLARE @DetailCount intDECLARE @Error int/* Validate input parameters. Assume success. */SELECT @RetCode = 1, @RetMsg = ''IF @TimesheetDetails IS NULLSELECT @RetCode = 0,@RetMsg = @RetMsg +'Timesheet line item(s) required.' + CHAR(13) + CHAR(10)/* Create a temp table parse out each Timesheet detail from inputparameter string,count number of detail records and create SQL statement toinsert detail records into the temp table. */CREATE TABLE #tmpTimesheetDetails(RE_Code varchar(50),PR_Code varchar(50),AC_Code varchar(50),WE_Date smalldatetime,SAT REAL DEFAULT 0,SUN REAL DEFAULT 0,MON REAL DEFAULT 0,TUE REAL DEFAULT 0,WED REAL DEFAULT 0,THU REAL DEFAULT 0,FRI REAL DEFAULT 0,Notes varchar(255),General varchar(50),PO_Number REAL,WWL_Number REAL,CN_Number REAL)SELECT @SQLBase ='INSERT INTO#tmpTimesheetDetails(RE_Code,PR_Code,AC_Code,WE_Da te,SAT,SUN,MON,TUE,WED,THU,FRI,Notes,General,PO_Nu mber,WWL_Number,CN_Number)VALUES ( 'SELECT @TimesheetCount=0WHILE LEN( @TimesheetDetails) > 1BEGINSELECT @SQLComplete = @SQLBase + LEFT( @TimesheetDetails,Charindex(';', @TimesheetDetails) -1) + ')'EXEC(@SQLComplete)SELECT @TimesheetCount = @TimesheetCount + 1SELECT @TimesheetDetails = RIGHT( @TimesheetDetails, Len(@TimesheetDetails)-Charindex(';', @TimesheetDetails))ENDIF (SELECT Count(*) FROM #tmpTimesheetDetails) <> @TimesheetCountSELECT @RetCode = 0, @RetMsg = @RetMsg + 'Timesheet Detailscouldn''t be saved.' + CHAR(13) + CHAR(10)-- If validation failed, exit procIF @RetCode = 0RETURN-- If validation ok, continueSELECT @RetMsg = @RetMsg + 'Timesheet Details ok.' + CHAR(13) +CHAR(10)/* RETURN*/-- Start transaction by inserting into Timesheet tableBEGIN TRANINSERT INTO timesheet.dbo.table1select RE_Code,PR_Code,AC_Code,WE_Date,SAT,SUN,MON,TUE,WE D,THU,FRI,Notes,General,PO_Number,WWL_Number,CN_Nu mberFROM #tmpTimesheetDetails-- Check if insert succeeded. If so, get ID.IF @@ROWCOUNT = 1SELECT @TimesheetID = @@IDENTITYELSESELECT @TimesheetID = 0,@RetCode = 0,@RetMsg = 'Insertion of new Timesheet failed.'-- If order is not inserted, rollback and exitIF @RetCode = 0BEGINROLLBACK TRAN-- RETURNEND--RETURNSELECT @Error =@@errorprint ''print "The value of @error is " + convert (varchar, @error)returnGO

View 2 Replies View Related

Insert Into Temp Table

Feb 22, 2004

Hi,
I am trying to insert into temp table multiple times and then pull everything out. How would I do that? I get records back, but everything is 0. Why? Here is my stored procedure.

CREATE PROCEDURE sp_SummaryReport
(
@startdate datetime,
@enddate datetime
)
AS
BEGIN
SET NOCOUNT ON

CREATE TABLE #CalcTemp (DataID bigint IDENTITY(1,1) NOT FOR REPLICATION, ReportType varchar(2), Volume int, NetEffect decimal(10,1), GrossEffect decimal(10,1), WeekEndDate datetime)


DECLARE @OnTime decimal(10,1)
DECLARE @UnControlled decimal(10,1)
DECLARE @Volume int
DECLARE @GrossEffect decimal(10,1)
DECLARE @NetEffect decimal(10,1)
DECLARE @WeekEndDate datetime
--ARS AA
SET @OnTime = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ARSScanType = 'D' AND ARSType='AA')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ARSScanType = 'D' AND ARSType='AA')
SET @Volume = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ARSScanType = 'D' AND ARSType='AA')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblARSData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('AA',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)
--ARS AN
SET @OnTime = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ARSScanType = 'D' AND ARSType='AN')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ARSScanType = 'D' AND ARSType='AN')
SET @Volume = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ARSScanType = 'D' AND ARSType='AN')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblARSData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('AN',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)
--ARS AC
SET @OnTime = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ARSScanType = 'D' AND ARSType='AC')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ARSScanType = 'D' AND ARSType='AC')
SET @Volume = (SELECT COUNT(DataID) FROM tblARSData WHERE (tblARSData.WeekEndDate BETWEEN @startdate AND @enddate) AND ARSScanType = 'D' AND ARSType='AC')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblARSData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('AC',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)
--General
SET @OnTime = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ReportType = 'GN' AND ScanType='D')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ReportType = 'GN' AND ScanType='D')
SET @Volume = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ReportType = 'GN' AND ScanType='D')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblShipData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('GN',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)
--Odessey
SET @OnTime = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ReportType = 'OD' AND ScanType='D')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ReportType = 'OD' AND ScanType='D')
SET @Volume = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ReportType = 'OD' AND ScanType='D')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblShipData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('OD',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)
--General
SET @OnTime = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND OnTimeFlag = 1 AND ReportType = 'HU' AND ScanType='D')
SET @UnControlled = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ControlFlag = 'U' AND ReportType = 'HU' AND ScanType='D')
SET @Volume = (SELECT COUNT(DataID) FROM tblShipData WHERE (tblShipData.WeekEndDate BETWEEN @startdate AND @enddate) AND ReportType = 'HU' AND ScanType='D')
SET @GrossEffect = ((@OnTime/@Volume) * 100)
SET @NetEffect = (((@OnTime + @UnControlled)/@Volume) * 100)
SET @WeekEndDate = (SELECT DISTINCT WeekEndDate FROM tblShipData)

INSERT INTO #CalcTemp(ReportType, Volume, NetEffect, GrossEffect, WeekEndDate)
VALUES ('HU',
@Volume,
@NetEffect,
@GrossEffect,
@WeekEndDate)


SELECTtblListReportType.ReportType AS 'Report Type',
tblListReportType.ReportID AS ReportID,
SUM(#CalcTemp.Volume) AS Volume,
CAST(SUM(#CalcTemp.NetEffect)/COUNT(#CalcTemp.DataID) as decimal(10,1)) AS 'Net % Effective',
CAST(SUM(#CalcTemp.GrossEffect)/COUNT(#CalcTemp.DataID) as decimal(10,1)) AS 'Gross % Effective'
FROM#CalcTemp
INNER JOIN tblListReportType ON LTRIM(RTRIM(LOWER(#CalcTemp.ReportType))) = LTRIM(RTRIM(LOWER(tblListReportType.ReportAbv)))
GROUP BYtblListReportType.ReportType,
tblListReportType.ReportID
END
GO

View 1 Replies View Related

How To Insert Into Temp Table

Nov 3, 2006

i have temp table name "#TempResult" with column names Memberid,Month,Year. Consider this temp table alredy has some rows from previuos query. I have one more table name "Rebate" which also has columns MemberID,Month, Year and some more columns. Now i wanted to insert rows from "Rebate" Table into Temp Table where MemberID.Month and Year DOES NOT exist in Temp table.

MemberID + Month + Year should ne unique in Temp table

View 8 Replies View Related

SQL 2012 :: Way Of Creating Temp Table

May 22, 2014

I am working with the SP tuning. I want to know clearly about the temp tables.Instead of Select * into #table, it is always better to create temp table structure and insert the data later.Is it true in the case, if the data is small? insert into #table (select colmn1, column 2 from TableA join Table B on JoinC on joinD on..If they use several joins, in that situation, which way of creating temp table would be better?

View 9 Replies View Related

Transact SQL :: Insert Data From Temp Table To Other Table

Oct 5, 2015

I want to insert the data from temp table to other table. Only condition is, it needs to sorted based on tool number and tool date. For example if we have ten records for tool number 1000, it should be order by tool number and then based on tool_dt. Both tables doesn't have any primary keys. Please find below my code. I removed all the unnecessary columns for simple understanding. INSERT INTO tool_summary  (tool_nbr, tool_dt) select tool_nbr, tool_dt from #tool order by tool_nbr, tool_dt...But this query is not working as expected. Data is getting shuffled.

Actual Data
Expected Result

1000
1-Aug
1000
1-Feb
1000
1-Jul
1000

[code]....

View 3 Replies View Related

How Do I Insert Into Existing Temp Table?

May 2, 2006

Hi,

How do I insert data into an existing temporary table? Note: I’m primarily a .NET programmer who has to do T-SQL to grab data from time to time.

What I am trying to do is this:
1) Put the scores for all the people who have completed a questionnaire into a temporary table called #GroupConfidence.
2) Add on a row at the end that gives an average for each score (ie the last row is an average of the column above).

I need my SP to give me a DataSet that I can throw straight to my .NET reporting engine (I don’t want to do any number crunching inside .NET) - that's why I want to add on the 'average' row at the end.


If I do this (below) the temporary table (#GroupConfidence) gets created and the values inserted.

-- Insert the results into the #GroupConfidence table
SELECTRTRIM(UC.FirstName + ' ' + UC.LastName) AS 'FullName',
RP.SubmitID,
RP.GL_Score,
RP.GP_Score,
RP.GPH_Score,
RP.DL_Score,
RP.MP_Score,
RP.Role_MI_Score,
RP.Role_ASXRE_Score,
RP.Role_APRA_Score,
RP.Overall_Score AS 'AllCategories'
INTO#GroupConfidence
FROMRodResultPercentages RP
JOIN#UsersCompleted UC ON UC.SubmitID = RP.SubmitID

My problem is that #GroupConfidence already exists so in fact I have this code below:

CREATE TABLE #GroupConfidence
([FullName] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[SubmitID] [int] NOT NULL,
[GL_Score] [decimal](19, 10) NOT NULL,
[GP_Score] [decimal](19, 10) NOT NULL,
[GPH_Score] [decimal](19, 10) NOT NULL,
[DL_Score] [decimal](19, 10) NOT NULL,
[MP_Score] [decimal](19, 10) NOT NULL,
[Role_MI_Score] [decimal](19, 10) NOT NULL,
[Role_ASXRE_Score] [decimal](19, 10) NOT NULL,
[Role_APRA_Score] [decimal](19, 10) NOT NULL,
[AllCategories] [decimal](19, 10) NOT NULL
)

-- Insert the results into the #GroupConfidence table
SELECTRTRIM(UC.FirstName + ' ' + UC.LastName) AS 'FullName',
RP.SubmitID,
RP.GL_Score,
RP.GP_Score,
RP.GPH_Score,
RP.DL_Score,
RP.MP_Score,
RP.Role_MI_Score,
RP.Role_ASXRE_Score,
RP.Role_APRA_Score,
RP.Overall_Score AS 'AllCategories'
INTO#GroupConfidence
FROMRodResultPercentages RP
JOIN#UsersCompleted UC ON UC.SubmitID = RP.SubmitID

So I get this error: Server: Msg 2714, Level 16, State 1, Line 109
There is already an object named '#GroupConfidence' in the database.


Thanks in advance,

Ian.

View 2 Replies View Related

Insert Temp Table Problem

Apr 11, 2008

Hi Everyone,

I insert data to #temp table by using 'select into'. Then I insert one extra row. when I select data, why it does not follow the order?
(the last insert should be in the last row but it becomes the first row)

Here is the simple script

Select name,code,dates into #temp From member Order By Dates

Insert #temp (name,code,dates)
select 'dave', '0', getdate()

select * from #temp

View 6 Replies View Related

SQL 2012 :: Temp Table Sort Order

Apr 3, 2013

Is there a way to change the order that "select * from #table" returns data? It doesn't appear to return data in the same order that it was inserted into the table. This wasn't a problem with the same code in SQL Server 2005.

View 5 Replies View Related

SQL 2012 :: Should Change SP To Run Select Into Temp Table

Mar 5, 2014

it runs over night, pulls 10.5m rows. Inserts into a table, from a select (so "insert...select", rather than "select into"), from many tables, grouping on a max. It's complex. During the day, it runs fine - maybe 25 minutes. At night it *sometimes* runs fine, but then sometimes takes 4hours.Checking this morning there were 230 threads open for this one query. Checking sys.dm_os_tasks and sys.dm_os_waiting_tasks there were no other wait types on that session_id. None at all. Checking activity monitor, most of the existing threads were suspended on the insert.

There are 24 cores, but NUMA'd. We have maxdop on the server of 8. The maxdop option on the query is 12, just to speed up the select. Index and Stats refreshed daily. We've eight identical tempdb data files, on a separate spindle. Checking those, they are filling up using the round robin correctly

Would the delay be due to SQL trying to combine so many 'select' threads into one 'insert' thread (as it can't insert in parallel; 2014 can, apparently. Upgrades not available!)Should i change the SP to run the select into a temp table (table variable?) with a maxdop of 12, then do the insert into the actual table using a maxdop of 1. Checking the execution plans for a table variable implies the subtree cost comes down from 2.5m to 357k. What's best - temp table or table variable?

View 9 Replies View Related

SQL 2012 :: Createing Temp Table But Got Error

May 27, 2014

I try to modify a code to create a temp table but got an error.

Declare @headerid Int
Declare @Providerid Int
BELOW CODE IS WORKING:
SELECT @headerid=HEADERID,@Providerid=PROVIDERID
FROM CLAIM WITH(NOLOCK) WHERE EDI_CLM_NUM= 123

[code]...

Error:
Incorrect syntax near '='.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

View 5 Replies View Related

SQL Server 2012 :: Adding New Row In Temp Table

May 12, 2015

I am trying to insert a single row in Temp table #InventoryItems . The temp table is mentioned in a curosor childcur_inventory. While looping through the cursor I have mentioned nested if else condition . In the Else condition where I have mentioned PRINT "Hello World" I want to insert a single row in the temp #InventoryItems. I trying to use Select Top 1 but the cursor is looping indefinitely trying to insert multiple record

I want to insert only one record with null values.

DECLARE childcur_inventory CURSOR FOR SELECT Structure_Number, State, Neighbor_State, Border_Bridge_Structure_Number FROM #InventoryItems
OPEN childcur_inventory
FETCH childcur_inventory INTO @Structure_Number, @State, @Neighbour_State, @Border_Bridge_Structure_Number

[Code] .....

View 5 Replies View Related

Insert Unique Rows In Temp Table

Nov 3, 2006

i have temp table name "#TempResult" with column names Memberid,Month,Year. Consider this temp table alredy has some rows from previuos query.  I have one more table name "Rebate" which also has columns MemberID,Month, Year and some more columns. Now i wanted to insert rows from "Rebate" Table into Temp Table where MemberID.Month and Year DOES NOT exist in Temp table.
MemberID + Month + Year should ne unique in Temp table

View 1 Replies View Related

INSERT INTO TEMP TABLE NOT WORKING IN SQL SERVER 7.

Dec 2, 1999

Hi I have the following Stored Proc which works in SQL Server 6.5 but not in SQL Server 7.0. All this Stored Proc does is Create a temp table, execute the DBCC ShowContig on a table and insert the results of the DBCC into a temp table. What am I missing. Thanks.

The code of the Stored Proc is:

/* This Stored Procedure Creates a temp table. (Step 1) */
/* Initializes a local variable @StirngToBeExecuted with */
/* a DBCC command. (Step 2) */
/* Step 3. The Command is Executed and the results of the */
/* DBCC command is inserted into Temp Table. */
/* Step 4. The results of the Temp table are shown on the */
/* Screen. */

/* This SQL Works Fine in SQL Server Version 6.5 */
/* In SQL Server 7.0 the results of the DBCC command is */
/* NOT getting inserted into the Temp table. WHY??? */

IF EXISTS (SELECT * from sysobjects where id = object_id('dbo.Test_sp') and sysstat & 0xf = 4)
drop procedure dbo.Test_sp
GO

CREATE PROCEDURE Test_sp

AS

DECLARE

@StirngToBeExecuted Varchar(100)

CREATE TABLE #temp( -- Step 1
OutputOfExecute Varchar(255)
)

-- Step 2
SELECT @StirngToBeExecuted = 'DBCC SHOWCONTIG (123456789)'


INSERT
INTO #temp exec (@StirngToBeExecuted) -- Step 3

SELECT * FROM #temp -- Step 4



DROP TABLE #temp --Drop the Temp Table

View 2 Replies View Related

Insert Into Temp Table Based On If Condition

Apr 12, 2006

hello all,this might be simple:I populate a temp table based on a condition from another table:select @condition = condition from table1 where id=1 [this will giveme either 0 or 1]in my stored procedure I want to do this:if @condition = 0beginselect * into #tmp_tablefrom products pinner joinsales s on p.p_data = s.p_dataendelsebeginselect * into #tmp_tablefrom products pleft joinsales s on p.p_data = s.p_dataendTha above query would not work since SQL thinks I am trying to use thesame temp table twice.As you can see the major thing that gets effected with the condictionbeing 0/1 is the join (inner or outer). The actual SQL is much biggerwith other joins but the only thing changing in the 2 sql's is the joinbetween products and sales tables.any ideas gurus on how to use different sql's into temp table based onthe condition?thanksadi

View 5 Replies View Related

SQL 2012 :: Import Txt Data File Into Temp Table?

Sep 30, 2014

In Access, I can import a txt file data(e.g. Claims.txt) as below specifications:

Choose the delimiter that separates your fields: Other (|)
First row contains field name: Yes
Text Qualifier:"

I need to create a store procedure to read txt file data (d:cliamcliams.txt) first column (ClaimNumber) into a temp table (#claim)

(This #claim table will use for my .Net program)

There about 5 txt files need to process every day.

View 1 Replies View Related

SQL 2012 :: Global Temp Table - Invalid Object Name

Feb 13, 2015

I have created a global temp table in Step1 of SQL Job.

I have used that in remaining steps of same job...i ran the job

But i got error message like invalid object name ##xxxxxxxx later i have included as tempdb..##xxxxxxxx also. the i got invalid reference for...

From my SSMS:-

But i was able to do select query for the same from my SSMS...

i have incorporated all steps in single step and completed job...

My question is why ##temp table created in step1 is not able to use in other steps of same job ?

SQL Server 2012 Enterprise Edition

View 2 Replies View Related

SQL 2012 :: Inserting Data Into Temp Table Using 2 While Loop

Apr 21, 2015

I want to insert data (month&year) from 2014 till now - into temp table using 2 while loop.

drop table #loop
create table #loop
(
seq int identity(1,1),
[month] smallint,
[Year] smallint

For some reason I cant not get 2015 data .

View 4 Replies View Related

Select From Multiple Tables, Insert In Temp Table

Feb 18, 2004

What's the best way to go about inserting data from several tables that all contain the same type of data I want to store (employeeID, employerID, date.. etc) into a temp table based on a select query that filters each table's data?


Any ideas?

Thanks in advance.

View 6 Replies View Related

SQL 2012 :: Import Excel XLSX Files Into Temp Table

Feb 18, 2014

I am having with trying to import XLSX files into SQL 2012 64 Bit.

I have installed the Access driver (AccessDatabaseEngine_x64.exe)

I have configured the script to run the following SP

sp_configure 'show advanced options', 1
GO
RECONFIGURE WITH OverRide
GO
sp_configure 'Ad Hoc Distributed Queries', 1

[Code] ....

So I first create my Temp Table

The run the SP above then I run the insert into the Temp table defined

INSERT INTO tempdb.dbo.TempTRBZ (IsNew,CoID, Zip, City, County,StateCode,Rate,Taxable,TaxShip,TaxLab,CountryID,StateID)

SELECT * FROM OPENROWSET( 'Microsoft.ACE.OLEDB.12.0','EXCEL 12.0;Database=C:TempNotInTrbzJan.xlsx;HDR=YES','SELECT * FROM [Data$]')

[Code] ....

The error message I get back is

Msg 7303, Level 16, State 1, Line 4
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

What I have set wrong on the import? Using SSIS at this point is not a real option.

View 0 Replies View Related

SQL 2012 :: Partially Contained Database And Temp Table Creation

Nov 20, 2014

As far as I know temp tables/objects will be created inside the default filegroup of the partially contained database and not in tempdb. Is it possible to either define a set of files dedicated to temp objects or define a second partially contained database dedicated to temp objects like tempdb?

View 0 Replies View Related

SQL Server 2012 :: Storing Data From Temp Table Into A Variable

Aug 4, 2015

I have created procedure that creates a temptable with the users from a certain business unit.

I need to save the output from the username field to my variable @TheUsers as I will be using this variable in ssrs.

CREATE TABLE #TEMP_TABLE
(
useriduniqueidentifier,
usernamevarchar(200),
unitiduniqueidentifier,
unitnamevarchar(200)

[Code] ....

View 6 Replies View Related

Transact SQL :: Insert Constant Value Along With Results Of Select Into Temp Table?

Dec 4, 2015

I'm trying to fill a temp table whose columns are the same as another table plus it has one more column. The temp table's contents are those rows in the other table that meet a particular condition plus another column that is the name of the table that is the source for the rows being added.

Example: 'permTable' has col1 and col2. The data in these two rows plus the name of the table from which it came ('permTable' in this example) are to be added to #temp.

Data in permTable
col1   col2
11,    12
21,     22

Data in #temp after permTable's filtered contents have been added

TableName, col1   col2
permTable, 11,     12
permTable, 21,     22

What is the syntax for an insert like this?

View 2 Replies View Related

Transact SQL :: How To Do Bulk Insert Into Temp Table From Text File

Sep 15, 2015

How do I do a bulk insert into a temp table from a text file. Text file looks like that:
 
ver_id TYPE
E57AB326-803C-436E-B491-398A255C919A 58
34D2A601-6BBA-46B1-84E1-3A805FDA3812 58
986E140C-62F1-48F1-B428-3571EBF00DA0 58

My statement looks like this:

CREATE TABLE [dbo].[tblTemp]([ver_id]  [nvarchar](255), [TYPE] [smallint]) 
GO
BULK INSERT [dbo].[tblTemp]
FROM 'C:v2.txt'
I keep receiving errors.

The error I receive is: Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 2 (TYPE).

View 2 Replies View Related

SQL 2005 Select Into Temp Table Then Insert Causes Null Issue

Jul 20, 2007

Here is the scenario that I cannot resolve



CREATE TABLE [dbo].[tEvents](

[EventID] [int] IDENTITY(1,1) NOT NULL,

[EventName] [varchar](1000) NOT NULL,

CONSTRAINT [PK_tEvent] PRIMARY KEY CLUSTERED

(

[EventID] ASC

)WITH FILLFACTOR = 90 ON [PRIMARY]

) ON [PRIMARY]



CREATE TABLE [dbo].[tEventSelections](

[EventSelectionID] [int] IDENTITY(1,1) NOT NULL,

[EventID] [int] NOT NULL,

[StatusPID] [int] NOT NULL,

CONSTRAINT [PK_tEventSelections] PRIMARY KEY CLUSTERED

(

[EventSelectionID] ASC

)WITH FILLFACTOR = 90 ON [PRIMARY]

) ON [PRIMARY]



then try this



SELECT e.eventName, es.statuspid

INTO #tmpTable

FROM tEventSelections ES

INNER JOIN tEvents E

ON E.EVentID = ES.EventID

INSERT INTO #tmpTable (eventName) values ('Another One')

DROP TABLE #tmpTable



this causes a null insert issue

(0 row(s) affected)

Msg 515, Level 16, State 2, Line 7

Cannot insert the value NULL into column 'statuspid', table 'tempdb.dbo.#tmpTable___________________________________________________________________________________________________________000000000130'; column does not allow nulls. INSERT fails.

The statement has been terminated.



So how do I allow the null, as the not null is coming from the ES table. But I want to allow the insert to happen without having to create the table first, this code works in SQL 2000 but fails in 2005, inserting all fileds into the insert also has it's own issues as some of the fields are delibertly left blank so in some circumstances the data returned to a grid displays correctly.



This method has been used in quite a lot of stored procedures and will be a nightmare to correct if each has to be edited.



One example of the use of is to return a dataset and then add a row at the bottom which is a sum of all the rows.



Regards

View 20 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved