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


ADVERTISEMENT

Drop Existing Temp Table

Nov 7, 2007

hello!! i am using a couple of temp tables for a select statement.
i need to drop the tables only if they exist before using them, because if i don't drop, then i will get this error:

There is already an object named '#Tmp01' in the database.

and if i try to drop the tables for the first time i run the query, then i will get an error saying that i cannot drop a table that doesn't exist.

i have tried using this sentence:

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = '#Tmp01') DROP TABLE #Tmp01
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = '#Tmp02') DROP TABLE #Tmp02
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = '#Tmp03') DROP TABLE #Tmp03

but it only seems to work with normal tables, since temp tables are not found in sysobjects.

any suggestions??


thnx

View 7 Replies View Related

Need Help In Copying A Temp Tables Contents To A Existing Table

Nov 8, 2006

I have a real table with an identity column and a trigger to populate this column.

I need to import / massage data for data loads from a different format, so I have a temp table defined that contains only the columns that are represented in the data file so I can bulk insert.

I then alter this table to add all the other columns so that it reflects all the columns in the real table. I then populate all the values so that this contains the data I need.

I then want to insert into the real table pushing the data from the temp table, however this gives me errors stating that the query returned multiple rows.

I specified all the columns in the insert grouping as well as on the select from the temp table.

ANY thoughts / comments are appreciated. This is beginning to drive me nuts.



Rob

View 5 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

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

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

Insert Error On Existing Table

Oct 10, 2006

I am having the below issue.

Duplicate Key Values

When inserting records into a table created through a RDA Pull(), many users experience duplicate key violations. One reason for this is Identity columns. SQL Server CE RDA does not set the seed on the Identity columns when a table is pulled.

Source: Microsoft SQL Server 2000 Windows CE Edition

Native Error: 25016

HR: DB_E_INTEGRITYVIOLATION

Description: Value violated the integrity constraints for a column or table.

Interface defining error: IID_IRowsetChange

Param = 0

Param = 0

Param = 0

Param =

Param =

Param =

This error can be returned when the user attempts to insert a row with an automatically incremented Identity column. With RDA, this usually occurs when a user pulls rows from the server and attempts to insert new rows before setting the seed and increment values for the Identity column. By default, the seed and increment values are both 1.

To correct this error, set the seed to the next highest number after the table is pulled, before allowing users to enter data.



What do they mean by setting the seed to the next highest level? I this the seed to the GUID row in the pulled table? How do you correctly do this with the ALTER table statement? The database that I am pulling has 21 tables, and would be a pain to have to do this. Does anyone have any other ideas as to why this won't work properly. If I clear out the data from the tables on the publishing server, I can add data to the pull as long as I want until I do another pull later. After I do that, I keep getting the above issue.

View 1 Replies View Related

Insert COUNT Into An Existing Table

Jan 31, 2008

I need to run a query and insert the count results and a name of another table into an existing table.

I have 20 jobs that import records from text files into seperate tables. When that completes I want the count to be sent to another table along with the table name that the count was run on. Any ideas? I can't get SELECT INSERT to work.

Matt

View 1 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

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 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

Create Insert Scripts For Existing Table?

Jan 6, 2007

What is the easiset way to create TSQL Insert scripts for each record in a table. Can this be accomplished with one of the tools in SQL Server 2005?

Thanks in advance

View 5 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

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

DB Engine :: How To Insert Excel File Data Into Temp Table

Jul 9, 2015

I have an Excel file with .csv extension . it has on sheet with name Sheet1.

Now, I'm trying to insert this Excel data into one #temp table. I tried with syntax:

----------------
Exec sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
Exec sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1; 

[Code] ...

But, I'm getting error:

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.

Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

If I'm executing for .xls file this statement is working finr and rows are inserted into #temp table. How to take excel file of .csv extension??

View 3 Replies View Related

Transact SQL :: Confirmation Of UNION ALL Query For INSERT INTO Temp Table

Jul 21, 2015

I have the following UNION ALL query with SELECT INTO @tblData temp table. I would like to confirm if my query is correct.

In my first SELECT statement, I have INSERT INTO @tblData.

Do I need another INSERT INTO @tblData again in my second SELECT statement after UNION ALL?

DECLARE @BeginDate as Datetime
DECLARE @EndDate as Datetime
SET @BeginDate = '7/1/2015'
SET @EndDate = '7/13/2015'
DECLARE @tblData table

[Code] ....

View 3 Replies View Related

SQL 2012 :: How To Prepend Value To Existing Value While Creating A Temp Column

Dec 5, 2014

I am looking for a way to create a temp column who's value would take the value of another column and prepend a value like this to it "domain". This is the Select statement I currently have:

SELECT Nalphakey,[Last Name],[First Name],[User Name],[E-mail Address],[User Name]
FROM SkywardUserProfiles

I understand how to create an Alias for an existing column, but not sure how to do what I am wanting. I also understand that the following will do the concatenation that I need, but I have only used it in an UPDATE query, and I'm not sure how to use it within a Select statement or if that's even possible:

domainName=CONCAT('domain',User Name);

View 2 Replies View Related

T-SQL (SS2K8) :: Moving Values From Temp Table To Another Temp Table?

Apr 9, 2014

Below are my temp tables

--DROP TABLE #Base_Resource, #Resource, #Resource_Trans;
SELECT data.*
INTO #Base_Resource
FROM (
SELECT '11A','Samsung' UNION ALL

[Code] ....

I want to loop through the data from #Base_Resource and do the follwing logic.

1. get the Resourcekey from #Base_Resource and insert into #Resource table

2. Get the SCOPE_IDENTITY(),value and insert into to

#Resource_Trans table's column(StringId,value)

I am able to do this using while loop. Is there any way to avoid the while loop to make this work?

View 2 Replies View Related

Temp Table Vs Global Temp Table

Jun 24, 1999

I think this is a very simple question, however, I don't know the
answer. What is the difference between a regular Temp table
and a Global Temp table? I need to create a temp table within
an sp that all users will use. I want the table recreated each
time someone accesses the sp, though, because some of the
same info may need to be inserted and I don't want any PK errors.

thanks!!
Toni Eibner

View 2 Replies View Related

Insert, And Replace If Already Existing

Feb 3, 2008

I am new and still not used to the SQL language model. Still can't think of a way to implement FOREACH.

I have a source table, T1, with three columns col1, col2, col3, and col4.


I have a destination table, T2, with the same four columns.


I want to move all the data from T1 to T2, deleting all those records in T2 where there exists in T1 a record with the same col1 AND col2 values.


In other words, a record is "uniquely" defined by the combination of col1 and col2.


What€™s the best way to achieve the above?


Thanks


HC

View 5 Replies View Related

Can I INSERT INTO A Temp Tbl Twice In One Stored Procedure

Mar 15, 2007

In my stored procedure I need to select some data columns and insert them into a #temp tbl and then select the same data columns again using a different from and put them into the same #temp tbl. It sounds like a union, can I union into a #temp tbl?
Any help here is appreciated.

View 4 Replies View Related

Insert On Existing Update In MS SQL Server?

Feb 6, 2007

HelloI used to work in a Sybase database environment. When I had to insert/update records in the database, I always used "insert on existingupdate", in this way, you didn't have to check whether a recordalready existed (avoid errors) and you were always sure that afterrunning the scripts, the last version was in the database.Now I'm looking for the same functionality in MS SQL Server, asked afew people, but nobody knows about such an option.Does anybody here knows the SQL Server counterpart of "insert onexisting skip/update"? If this doesn't exist, this is a minus forMS ;).Greetz,Bart

View 4 Replies View Related

Bulk Insert Permissions For Temp Tables

Feb 21, 2001

Does anyone know what permissions are required to run bulk insert to a temp table?

I've got a procedure that creates a temp table and runs bulk insert on it. Only problem is that it seems that only the dbo can run it. Anyone else gets the following error:
"The current user is not the database or object owner of table '#bulk'. Cannot perform SET operation."

Alternatively, does anyone know how to submit a scheduled job as a different user?

I've got my import system set up to create a scheduled job that kicks off right away. The job runs the 1st step which includes a bulk insert. The second step checks if the first step completely failed or not. Works great except that when the user runs the submission procedure, it comes back with that error.

Microsoft's brain-dead bulk insert command....aaargh. Every method around it's design flaws is blocked by another design flaw.

View 1 Replies View Related

Insert Into Temp Results Of A Union Query

Nov 20, 2007

Hi,
I have follwing union query. I want to put this all in a temp table.

select Store_Id,batchnumber
From
Adjustments where updatedDt between '10/30/2007' and '11/20/2007' and Store_id in(8637 ,8641)
group by Store_Id, batchnumber
Union
select DestinationId,b.batchNumber
from
batch b
inner join Carton C on C.Carton_Id = b.General_ID
inner join Document d on d.Document_Id = c.Document_Id
where b.BatchType = 'Warehouse' and b.TranTable = 'Carton'
and (d.DestinationId in (8637 ,8641) ) and c.UpdatedDt Between '10/30/2007' and '11/20/2007'
Union
select d.DestinationId,b.Batchnumber
From
batch b
inner join Document d
on d.Document_Id = b.General_Id
where b.BatchType = 'TransferIn' and b.TranTable = 'Document'
and (d.DestinationId in (8637,8641) ) and d.UpdatedDt Between'10/30/2007' and '11/20/2007'
Union
select d.SourceId,b.batchNumber
From
batch b
inner join Document d
on d.Document_Id = b.General_Id
where b.BatchType = 'TransferOut' and b.TranTable = 'Document'
and (d.SourceId in (8637,8641) ) and d.UpdatedDt Between'10/30/2007' and '11/20/2007'
order by batchnumber

Kindly advice.

Thanks
Renu

View 2 Replies View Related

Insert Into #temp Exec Sproc Not Working

Aug 15, 2005

Hi,I have a sproc with 5 params that takes about 40 seconds to return.But when I Create a Temp table and do aInsert Into #tempExec sproc param1, param2, param3, param4, param5it never returns...any ideas?Thanks,Bill

View 1 Replies View Related

Access Permissions To Bulk Insert On # Temp Tables

Oct 24, 2007



Hi ,

I am a newbie and i need to provide access for developer for him to use bulk insert ... on temp tables.
what permission do i need to provide the developer i cannot provide bulkadmin permission to him what are the other ways to provide him the access.

Please help me with this.

View 4 Replies View Related

DB Engine :: Performance Tuning Temp DB Slow INSERT From VIEW

May 16, 2015

I am running A View that INSERTS into #Temp Table - On Only Certain Days the INSERT Speed into #tempDB is so slow.
 
Attached snapshot that shows after one minute so many few records are inserted - and it dosent happen every day somedays its very fast. 

View 3 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







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