Newbie How To Create Temp Table And Populate

Sorry guys I know this is easy but I've been looking for about an hour for a straight forward explanation.
I want to store a user's wish list while they browse the site, then they can send me an enquiry populated with their choices.
Basically, a shopping cart!
I thought of using session variables and string manipulations but I am more comfortable with DB queries.
a simple 4 column table would cover everything.
SQL server and VBScript

View Replies


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

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 Replies View Related

Loop Through A Recordset To Populate Columns In A Temp Table

I want to take the contents from a table of appointments and insert theappointments for any given month into a temp table where all theappointments for each day are inserted into a single row with a columnfor each day of the month.Is there a simple way to do this?I have a recordset that looks like:SELECTa.Date,a.Client --contents: Joe, Frank, Fred, Pete, OscarFROMdbo.tblAppointments between ...(first and last day of the selected month)What I want to do is to create a temp table that has 31 columnsto hold appointments and insert into each column any appointments forthe date...CREATE TABLE #Appointments (id int identity, Day1 nvarchar(500), Day2nvarchar(500), Day3 nvarchar(500), etc...)Then loop through the recordset above to insert into Day1, Day 2, Day3,etc. all the appointments for that day, with multiple appointmentsseparated by a comma.INSERT INTO#Appointments(Day1)SELECTa.ClientFROMdbo.tblAppointments = (...first day of the month)(LOOP to Day31)The results would look likeDay1 Day2 Day3 ...Row1 Joe, PeteFrank,FredMaybe there's an even better way to handle this sort of situation?Thanks,lq

View Replies View Related

Boolean: {[If [table With This Name] Already Exists In [this Sql Database] Then [ Don't Create Another One] Else [create It And Populate It With These Values]}

the subject pretty much says it all, I want to be able to do the following in in code):
{[If [table with this name] already exists [in this sql database] then [ don't create another one] else [create it and populate it with these values]}
How would I do this?

View Replies View Related

&"Column Name Or Number Of Supplied Values Does Not Match Table Definition&" When Trying To Populate Temp Table


I am receiving the following error:

Column name or number of supplied values does not match table definition

I am trying to insert values into a temp table, using values from the table I copied the structure from, like this:

SELECT TOP 1 * INTO #tbl_User_Temp FROM tbl_User

INSERT INTO #tbl_User_Temp EXECUTE UserPersist_GetUserByCriteria @Gender = 'Male', @Culture = 'en-GB'

The SP UserPersist_GetByCriteria does a
"SELECT * FROM tbl_User WHERE gender = @Gender AND culture = @Culture",
so why am I receiving this error when both tables have the same

The error is being reported as coming from UserPersist_GetByCriteria on the "SELECT * FROM tbl_User" line.


View Replies View Related

I Can't Create A Temp Table

Hi all!I have a problem with a temp table.I start creating my table:bdsqlado.execute ("CREATE TABLE #MyTable ...")There is no error. The sql string has been tested and when it'sexecuted in the sql query analyzer it really creates the table.After creating the table, I execute an insert statement:bdsqlado.execute ("INSERT INTO #MyTable VALUES(...) "It returns an error like this: "Invalid Object Name #MyTable"I don't understand what's wrong. If I execute both sql sentences inthe SQL Query Analyzer it works perfectly.I use the same connection to execute both statements and I don't closeit before the INSERT is executed.I think it may be something related to dynamic properties of theconnection, but I'm not sure. It's just an idea.Please I need help.Thanks a lot,

View Replies View Related

Using A Variable To Create Temp Table

Can someone send me an example of creating a variable to use instead of a temp table? I cannot find an example on books on line, but know it is possible in SQL2000.


View Replies View Related

How Can I Create A Temp Table On A Linked Server?


I have a local SQL2005 server with a linked SQL2000 server. I would like to know how to create a temporary table in the remote server in such a way that I can make an inner join as follows; my idea is to optimized a distributed query by doing so:

create table #myRemoteTempTable

insert into #myRemoteTempTable
select * from myLocalTable

update myRemoteTable
from myRemoteTable
inner join #myRemoteTempTable on #myRemoteTempTable.ID=myRemoteTable.ID

View Replies View Related

Find The Datatypes That Where Used To Create A Temp Table

Is there a way to find out what the datatypes of a temp table are?


select cust_code, cust_name, cust_state
into #customers
where cust_state = 'TX'

I would like to know what datatypes SQL used when creating #customers.

Thank you for all the help.

View Replies View Related

Create Temp Table/loop Through Records

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 Replies View Related

Create A View Or Temp Table From 2 Tables

I have 2 tables:

Customer Table: ID, OrderID (composite key)

100, 1
100, 2
200, 3
200, 1
Order Table: OrderID, Detail

1, Orange
2, Apple
3, Pineaple

Assuming each customer always orders 2 items. I need to create a SQL query that shows as following (a view or a temp table is OK). How do I do that?

CustomerID, Order Detail1, Order Detail2

100, Orange, Apple
200, Pineaple, Orange

View Replies View Related

How Do I Create A Temp Table As The Beginning Of A Process Flow?

am new to SQL Server and I am struggling.

SQL Server Integration Services Designer Version

SQL Server Management Studio 9.00.1399.00

would like to
create a temp table
load the temp table from a flat file
insert into a destination table the rows from the temp table where NOT EXIST the
primary key of the destination table.


File Source will not accept that a resource will be available that does not yet
exist (the temp table)

set the Flat File Source to €œIgnore Failure€? and ran the package. It ran with
warnings but did not insert the new rows.

€œIgnore Duplicates€? radio button is €œgrayed out€? because the index is clustered

I could work around this thing by keeping a table just for purposes of this
process flow. I am opposed to that philosophically and would prefer to do this
in the way that I consider appropriate€¦is there a solution?


View Replies View Related

Create Temp Table To Store Data From Database(mssql)

I am a starter of and trying to build a web application. Do anyone know how to create a temp table to store data from database? I need to extract data from 3 different tables (Profile,Family,Quali). Therefore, i need to use 3 different queries to extract from the 3 tables and then store it in the temp table. Then, i need to output the data from temp table to the screen. Do anyone can help me?

View Replies View Related

Best Practice: Use Values In WHERE Clause Or Create And Join Temp Table ?

I am using a SQL back end to dynamically populate an report/page.
As the data I'm interrogating is created from a tree control, I'm having to use a recursive function to retrieve the data into a series of ID values. This all happens at the moment in a DataTable manipulated with c# code. So my ID values end up in this datatable.
 My problem is that I am then performing a crosstab query in SQL Server 2000 and these ID are required as part of that query.
 Should I create a temp table and join this into the query or should i feed in a series of ID values into a where clause?
 Any help gratefully appreciated.

View Replies View Related

Create Temp Table On Linked Server From Local Server


I would like to join two tables: one on a local server which I have admin access to and another server which I only have read access. The local table is very small, but the remote table is very large.

If I look at Query Analyzer's execution plan, it appears that the join will be done locally (i.e. the entire table is transferred from the remote server and then joined to my local table). Is there a way to create a temp table using linked servers, transfer my small local table to the remote server and then perform the join on the remote server? In the past, I have been able to use openquery to restrict the data to a small subset that is transferred but the local table is a little too large for that.

I appreciate any advice / guidance anyone can offer me!

View Replies View Related

CREATE A Temp Table Via &"EXEC (@SQL)&"

I need to create a dynamic temporary table in a SP. Basically, I am using the temp table to mimic a crosstab query result. So, in my SP, I have this:--------------------------------------------------------------------------------------- Get all SubquestionIDs for this concept-------------------------------------------------------------------------------------DECLARE curStudySubquestions CURSOR LOCAL STATIC READ_ONLY FOR SELECT QGDM.SubquestionID, QGDM.ShortName, QGDM.PosRespValuesFROM RotationMaster AS RM INNER JOIN RotationDetailMaster AS RDM ON RM.Rotation = RDM.Rotation INNER JOIN QuestionGroupMaster AS QGM ON RDM.QuestionGroupNumber = QGM.QuestionGroupNumber INNER JOIN QuestionGroupDetailMaster AS QGDM ON QGM.QuestionGroupNumber = QGDM.QuestionGroupNumberWHERE RM.Study = @StudyGROUP BY QGDM.SubquestionID, QGDM.ShortName, QGDM.PosRespValuesHAVING QGDM.SubquestionID <> 0--------------------------------------------------------------------------------------- Dynamically create a Temp Table to store the data, simulating a pivot table-------------------------------------------------------------------------------------SET @Count = 2SET @SQL = 'CREATE TABLE #AllSubquestions (Col1 VARCHAR(100)'OPEN curStudySubquestionsFETCH NEXT FROM curStudySubquestions INTO @SubquestionID, @ShortName, @PosRespValuesWHILE @@FETCH_STATUS = 0BEGIN SET @SQL = @SQL + ', Col' + CAST(@Count AS VARCHAR(5)) + ' VARCHAR(10)' SET @Count = @Count + 1 FETCH NEXT FROM curStudySubquestions INTO @SubquestionID, @ShortName, @PosRespValues ENDSET @SQL = @SQL + ', ShowOrder SMALLINT)'CLOSE curStudySubquestionsPRINT 'Create Table SQL:'PRINT @SQLEXEC (@SQL)SET @ErrNum = @@ERROR IF (@ErrNum <> 0) BEGIN PRINT 'ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!' RETURN ENDPRINT '*** Table Created ***'-- Test that the table was createdSELECT *, 'TEST' AS AnyField FROM #AllSubquestions The line PRINT @SQL produces this output in Query Analyzer (I added the line breaks for forum formatting):CREATE TABLE #AllSubquestions (Col1 VARCHAR(100), Col2 VARCHAR(10), Col3 VARCHAR(10), Col4 VARCHAR(10), Col5 VARCHAR(10), Col6 VARCHAR(10), Col7 VARCHAR(10), ShowOrder SMALLINT) However, the SELECT statement to test the creation of the table produces this error:*** Table Created ***Server: Msg 208, Level 16, State 1, Procedure sp_SLIDE_CONCEPT_AllSubquestions, Line 73Invalid object name '#AllSubquestions'. It appears that the statement to create the table works, but once I try to access it, it doesn't recognize its existance. Any ideas?

View Replies View Related

URI Key Held In Seperate Table To Automatically Populate PK In Another Table.

I have a table for which I wish to keep the index€™s off in a separate table. The trouble being that the database has to keep legacy support for a bunch of Access Interfaces that use linked tables to the database.

CREATE TABLE [dbo].[Tb_Students](
[student_uri] [int] NOT NULL,
[student_ref] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
[fname] [nvarchar](18) COLLATE Latin1_General_CI_AS NOT NULL,
[sname] [nvarchar](25) COLLATE Latin1_General_CI_AS NOT NULL


CREATE TABLE [dbo].[Ti_Student_Uri](
[next_uri] [int] NOT NULL

I also have a stored procedure for getting the next URI due:

CREATE PROCEDURE [dbo].[sp_get_next_Student_uri]
-- Add the parameters for the stored procedure here

(@uri integer output, @jump integer= 1)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
-- Insert statements for procedure here
SELECT @uri = next_uri
FROM Ti_Student_Uri
UPDATE Ti_Student_Uri
set next_uri=next_uri+@jump
WHERE next_uri = @uri
if @@rowcount <> 1
exec sp_get_next_Student_uri @uri output, @jump
commit transaction

Now as you can guess this is fine from my C# interface as this automatically grabs the next key from the URI table and populates the new tuple in Tb_Students. The access interface could do the same but I would rather not edit this client so I was wondering if what would be the best way to automatically insert the next key on a new record?

If it helps the access interface uses a view to access the Tb_Students and other tables.

View Replies View Related

Temp Table Vs Global Temp Table

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.

Toni Eibner

View Replies View Related

Create Temp Talbe

I'm trying to create a temp table in the stored procedure.the syntex is the following:create st_procvariables declaredif something >0create temp table #Table1if something <0create temp table #Table1SQL Compiler complains about the second create.thanks

View Replies View Related

Help For Newbie: How To Create An Autonumber

Hi guys/gals. An intro, I've just pick up some database basic skills and currently doing a simple project.

I really need advise on how do I create a field that can generate autonumbering for eg. scenario

There are 3 types of service_id like CTXXXX, GPXXXX, and STXXXX (where XXXX are running numbers). What I need is to have the XXXX auto generate and running. Also if I were to delete an old record for example CT0033, the latest number eg. CT1111 will not be changed to cover up for the missing CT0033.

I apologize if the description is a bit improper, but I'm new to this. Really appreciate anyone that can help. Thanks!! :o

View Replies View Related

How Do You Create ##Temp Tables If They Don't Exist, Use Them If They Do?

I have two SPs, call them Daily and Weekly. Weekly will always callDaily, but Daily can run on its own. I currently use a global temptable because certain things I do with it won't work with a local temptable or table variable.I have been trying to get code so that if the table already exists, itjust keeps going and uses it, but creates the temp table if it doesn'texist. Unfortunately, no matter how I try to do it, it always attemptsto create it, raising an error and breaking the code.create table ##load_file_log (id int identity(1,1),contentsvarchar(1000))insert into ##load_file_log (contents) values ('test record')IF object_id('tempdb..##load_file_log') IS not NULLprint 'exists'ELSEcreate table ##load_file_log (id int identity(1,1),contentsvarchar(1000))select * from ##load_file_logdrop table ##load_file_logIf I change it to IS NULL, the same error occurs (Server: Msg 2714,Level 16, State 1, Line 7There is already an object named '##load_file_log' in the database.)I have found one way to do it, but it seems a bit...clunky.IF object_id('tempdb..##load_file_log') IS NULLexec ('create table ##load_file_log (id int identity(1,1),contentsvarchar(1000))')I'll use that for now, but is there something I missed?Thanks.

View Replies View Related

How To Create A Sql Job For Truncating Temp Tables


How to create a sql job for truncating temprary tables?


give a sql job for truncating temprary tables?

Thanks in advance

View Replies View Related

SSIS Create Large Temp Files!!!


I created a SSIS solution for reading data from dbase and storing them in SQL Server. In a ForEachDirectory-Loop up to one thousand dbase files are read and stored. The system where the packages are running has 16 GB RAM.
For the first few hundred dbase files everything goes fine, but then, the RAM seems not to suffice any more and a temp file is created (I changed the path in BufferTempStoragePath).

How can it be that there is a need to create temp files if there is so much RAM available?
Why is the RAM filled more and more during the SSIS package execution?
Is there anything I can do to release some of it? (it is running in a loop and there is no need to store all the data)
Could it be caused by dbase?? (I use Microsoft Jet 4.0 OLE DB Provider)

Another thing is that the temp file is not stored in the path I set in BufferTempStoragePath.
There are sufficient permissions set, but temp file is still created in user temp folder...

Any kind of help is very much appreciated!

Best Regards,

View Replies View Related

How To Create A Recordset That Joins 3 Temp Tables

I have an stp where I want to return a Recordset via a SELECT that joins 3 temp tables...

Here's what the temp tables look like (I am being brief)...


CREATE TABLE #PayPeriods (PayPeriodIndex INTEGER, StartDate DATETIME, EndDate DATETIME)

CREATE TABLE #Statistics (EmpID INTEGER, PayPeriodIndex INTEGER, HoursWorked REAL)

The #Employees table is populated for all employees.

The #PayPeriods table is populated for each calandar week of the year (PayPeriodIndex=0 to 51).

The #Statistics table is populated from data within another permanent table.

Some employees do not work all 52 weeks.

Some employees do not work any of the 52 weeks.

So, the #Statistics table doesn't have all possible combinations of Employees and PayPeriods.

I want to return a Recordset for all possible combinations of Employees and PayPeriods...

Here's a SELECT that I have used...

SELECT e.EmpId, e.Name, pp.PayPeriodIndex, ISNULL(s.HoursWorked,0)

FROM #Statistics s

LEFT OUTER JOIN #Employees e....

LEFT OUTER JOIN #PayPeriods pp ....

WHERE s.EmpId = e.EmpId

AND s.PayPeriodIndex = pp.PayPeriodIndex

I have had no luck with this SELECT.

Can anybody help???


View Replies View Related

Using Trigger To Populate Another Table

Hi all,I have two tables tbl_A and tbl_B.Table Definitions:tbl_A (field_1, field_2, field_3)tbl_B (field_1, field_2)I would like to populate tbl_B when a record is inserted into tbl_A.Note that tbl_A.field_1 = tbl_B.field_1 and tbl_A.field_2 =tbl_B.field_2 .How do I write a trigger on tbl_A to get the corresponding recordinserted into tbl_B?RegardsJune.....

View Replies View Related

Trigger To Populate Another Table.

Hi.I have a problem I hope someone can help me with.I have a database of events. Each event has a date and a duration(days).What I need to do is to be able to display search for events on someweb pages. My problem is that if an event is on say 15 nov 2004 andhas a duration of 3 days, at the moment if someone searches for the16th nov 2004 that event wont show up. To solve this what I have triedto do is put a trigger on my events table that populates another tableeach time a record is inserted. In the other table (orderedevents) anentry is added for each day specified in the duration field. I can thequery this table for the search. For example if this is added into theevents tableTitle: Event1Date: 15/11/2004Duration: 3Then this would be added to the orderedevents tableTitle: Event1Date: 15/11/2004Duration: 3Title: Event1Date: 16/11/2004Duration: 3Title: Event1Date: 17/11/2004Duration: 3This is what I have got so far. Someone kindly helped me with thisbefore but they had developed it on MySql, I'm using Sql Server and itdoesn't seem to work. All it does is add a blank row to OrderedEvents.Can anyone suggest any amendments that will make it work on SqlServer?CREATE Trigger TriggerInsertOrderedEventsON eventsFOR INSERTASSET NOCOUNT ONDECLARE @CountDuration int,@FixedDuration int,@eventdate datetime,@EventTitle varcharSET @CountDuration = 0SET @EventTitle = (SELECT EventTitle FROM inserted)SET @FixedDuration = (SELECT EventDuration FROM inserted)SET @EventDate = (SELECT EventDate FROM inserted)WHILE (@CountDuration <= @FixedDuration - 1)BEGININSERT OrderedEvents (Eventdate,EventDuration,EventTitle)VALUES(dateadd(day,@CountDuration,@EventDate),@Fix edDuration,@EventTitle)SET @CountDuration = @CountDuration + 1ENDSET NOCOUNT OFFThanks in advance.

View Replies View Related

How To Populate A Table From A Sql Statement

In a Data Flow Task, I have an OLE DB source that uses the following SQL Statement;


--First create a table

DECLARE @CategoryTable TABLE
(ColID Int,
ColCategory varchar(60),
ColValue varchar(500)

--and fill it

INSERT INTO @CategoryTable
(ColID, ColCategory, ColValue)
LEFT(RawCollectionData,CHARINDEX(':',RawCollection Data)),
LTRIM(SUBSTRING(RawCollectionData,CHARINDEX(':',Ra wCollectionData)+1,255))
FROM Collections_Staging

--Assign an ID to each block of data for each occurance of 'Reason:'

SET @ID = 1
UPDATE @CategoryTable
SET [ColID] = CASE WHEN ColCategory = 'Reason:' THEN @ID - 1 ELSE @ID END,
@ID = CASE WHEN ColCategory = 'Reason:' THEN @ID + 1 ELSE @ID END

--Then put the data together

SELECT --cast to Nvarchar for MSAccess
CAST(a.ColValue as Nvarchar(30)) AS OrderID,
COALESCE(CAST(b.ColValue as Nvarchar(30)),'') AS SellerUserID,
COALESCE(CAST(c.ColValue as Nvarchar(100)),'') AS BusinessName,
COALESCE(CAST(d.ColValue as Nvarchar(15)),'') AS BankID,
COALESCE(CAST(e.ColValue as Nvarchar(15)),'') AS AccountID,
COALESCE(CAST(SUBSTRING(f.ColValue,CHARINDEX('$',f .ColValue)+1,500)AS DECIMAL(18,2)),0) AS CollectionAmount,
COALESCE(CAST(g.ColValue as Nvarchar(10)),'') AS TransactionType,
WHEN h.ColValue LIKE '%Matching Disbursement%' THEN NULL
ELSE CAST(h.ColValue AS SmallDateTime)
END AS DisbursementDate,
--COALESCE(h.ColValue,'') AS DisbursementDate,
WHEN i.ColValue LIKE '%Matching Disbursements%' THEN NULL
WHEN CAST(LEFT(REVERSE(i.ColValue),4)AS INT) > 1000 THEN CAST(i.ColValue AS SmallDateTime)
WHEN LEFT(REVERSE(i.ColValue),4) = '1000' THEN NULL
END AS ReturnDate,
--COALESCE(i.ColValue,'') AS ReturnDate,
COALESCE(CAST(j.ColValue as Nvarchar(4)),'') AS Code,
COALESCE(CAST(k.ColValue as Nvarchar(255)),'') AS CollectionReason

FROM @CategoryTable a
LEFT JOIN @CategoryTable b ON b.ColID = a.ColID AND b.ColCategory = 'Seller UserId:'
LEFT JOIN @CategoryTable c ON c.ColID = a.ColID AND c.ColCategory = 'Business Name:'
LEFT JOIN @CategoryTable d ON d.ColID = a.ColID AND d.ColCategory = 'Bank ID:'
LEFT JOIN @CategoryTable e ON e.ColID = a.ColID AND e.ColCategory = 'Account ID:'
LEFT JOIN @CategoryTable f ON f.ColID = a.ColID AND f.ColCategory = 'Amount:'
LEFT JOIN @CategoryTable g ON g.ColID = a.ColID AND g.ColCategory = 'Transaction Type:'
LEFT JOIN @CategoryTable h ON h.ColID = a.ColID AND h.ColCategory = 'Disbursement Date:'
LEFT JOIN @CategoryTable i ON i.ColID = a.ColID AND i.ColCategory = 'Return Date:'
LEFT JOIN @CategoryTable j ON j.ColID = a.ColID AND j.ColCategory = 'Code:'
LEFT JOIN @CategoryTable k ON k.ColID = a.ColID AND k.ColCategory = 'Reason:'

WHERE a.ColCategory = 'Order ID:'


This statement parses. I can preview the data. I've tried to set up both an OLE DB destination to a SQL Server table and an MS Access table destination (Jet). In either case, the data will not populate the tables. I set up a Data Viewer, and no data appears in the Viewer. With the Access destination, I have the package set up to run in 32 bit mode.

If data appears in the preview, then why doesn't the data appear in the data viewer, and why will the data not populate either of the destination tables?

Thank you for your help!


View Replies View Related

Populate The Fact Table


can any body tell me how to populate the fact table from base tables.

View Replies View Related

How To Populate The Fact Table

databse name: bookorder


customer (customerid,l_name,f_name,city, district,country)

Now populate the datawarehouse name: book_orderdw
having fact table & three dimension tables given below from the above bookorder database

fact table


dimension tables

dimtime(timeid,orderdate,dayofweek, month, year)

Now I have to populate the fact & dimension tables by writing sql scripts.
Now I have already populated the dimension tables by writing sql script,
But I have to populate the fact table taking into account, here I am facing problem in wriring sql script

(i) unit_price is taken from the book base table with reference to the isbn
(ii) sales_quantity is taken from the order_detail.quantity with reference to table cust_order(via orderid & orderdate)
(iii) discount_price is determined dependent on the quantity. if the quantity > 20 then discount 20 %(i.e discount_price = 0.8 * unit_price). if quantity < 10, no discount i.e normal price. if quantity between 10 and 20, discount 10%. Note that the quantity is determined based on each order of each customer, thus if the same book appears at multiple positions in an order, those positions shall be grouped together. This could happen because the pk of the order_detail table is order_id + item no, not order_id + isbn
(iv) sales_amount is sales_quantity * discount_price

View Replies View Related

Populate Field From Another Table

I have 2 tables in a parent->child relationship. The primary key for the parent table is moving to a new column (that is an Identity). I'd like to relink the tables using the identity field.

Here's the structure:
refid int (Identity) - NEW PK
orderid char(9) - OLD PK

orderdetailid int - PK
orderid char(9) - Old link to parent
refid int - New link to parent

I've populated refid in the parent. I just need to populate the refid column in the child. I have a VFP background. In VFP I would have looped through the child, found the matching record in the parent, then transfered the data over. I don' t have a clue how to do this in TSQL.


View Replies View Related

Copyrights 2005-15, All rights reserved