Transact SQL :: Table Structure - Inserting Data From Other Temp Table

Aug 14, 2015

Below is my table structure. And I am inserting data from other temp table.

CREATE TABLE #revf (
[Cusip] [VARCHAR](50) NULL, [sponfID] [VARCHAR](max) NULL, GroupSeries [VARCHAR](max) NULL, [tran] [VARCHAR](max) NULL, [AddDate] [VARCHAR](max) NULL, [SetDate] [VARCHAR](max) NULL, [PoolNumber] [VARCHAR](max) NULL, [Aggregate] [VARCHAR](max) NULL, [Price] [VARCHAR](max) NULL, [NetAmount] [VARCHAR](max) NULL,

[Code] ....

Now in a next step I am deleting the records from #revf table. Please see the delete code below

DELETE
FROM #revf
WHERE fi_gnmaid IN (
SELECT DISTINCT r2.fi_gnmaid
FROM #revf r1, #revf r2

[Code] ...

I don't want to create this #rev table so that i can avoid the delete statement. But data should not affect. Can i rewrite the above as below:

SELECT [Cusip], [sponfID], GroupSeries, [tran], [AddDate], [SetDate], [PoolNumber], [Aggregate], [Price], [NetAmount], [Interest],
[Coupon], [TradeDate], [ReversalDate], [Description], [ImportDate], MAX([fi_gnmaid]) AS Fi_GNMAID, accounttype, [IgnoreFlag], [IgnoreReason], IncludeReversals, DatasetID, [DeloitteTaxComments], [ReconciliationID],

[Code] ....

If my above statement is wrong . Where i can improve here? And actually i am getting 4 rows difference.

View 5 Replies


ADVERTISEMENT

Transact SQL :: Update Table With Its Value And Data From Row In Temp Table For Matching Record?

Oct 25, 2015

I have a temp table like this

CREATE TABLE #Temp
 (
  ID int,
  Source varchar(50),
  Date datetime,
  CID varchar(50),
  Segments int,
  Air_Date datetime,

[code]....

Getting Error

Msg 102, Level 15, State 1, Procedure PublishToDestination, Line 34 Incorrect syntax near 'd'.

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

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

Transact SQL :: Inserting Distinct Data From One Table To Another

Aug 19, 2015

I have 2 tables: Source Table - IncidentDimNew and Destination Table - IncidentDimNew with identical columns: Id and CreatedDate but the data is different.

I would like to insert distinct data from those 2 columns of 1st table into the same 2 columns into the 2nd table but I onlt want to replace the values in the 2nd table where the Created Date is > 2015-04

I compiled the code in order to get the information I want from 2 tables:

Source Table
SELECT
COUNT(Id),
LEFT(CONVERT(VARCHAR(10)), CreatedDate, 126), 7)
FROM
IncidentDimNew

[Code] ...

This is the code I wrote in order to do it
                     
INSERT INTO IncidentDim 
[Id]
      ,[CreatedDate]
     SELECT
[Id]
,[CreatedDate]

FROM
IncidentDimNew

where left(CONVERT(VARCHAR(10), CreatedDate, 126),7) > '2015-04'

GO

But what it does it's gives the SUM of the values in the corresponding rows where the values are not null which I don't want.

So  how do I leave the values as is from table IncidentDim and insert new values as it is from IncidentDimNew where the Created Date is > 2015-04?

View 2 Replies View Related

Transact SQL :: Dynamically Alter Schema Of Stage Table When Source Table Structure Changed?

Oct 25, 2015

we have a table in our ERP database and we copy data from this table into another "stage" table on a nightly basis. is there a way to dynamically alter the schema of the stage table when the source table's structure is changed? in other words, if a new column is added to the source table, i would like to add the column to the stage table during the nightly refresh.

View 4 Replies View Related

Transact SQL :: Present Data In Presentation Layer After Removing Temp Table?

May 21, 2015

Inside of stored procedure you have the code

create table #datatable (id int,
name varchar(100),
email varchar(10),
phone varchar(10),
cellphone varchar(10),
none varchar(10)
);
insert into #datatable
exec ('select *
from datatable
where id = 1')
select * from #datatable

I still want to retrieve the data and present it in the software's presentation layer but I still want to remove the temp table in order to reduce performance issue etc.

If I paste the code DROP

TABLE #datatable after
insert into #datatable
exec ('select *
from datatable
where id = 1')

Does it gonna work to present the data in the presentation layer after removing the temp table?

The goal is to retrieve the data from a stored procedure and present it in the software's presentation layer and I still need to remove the temptable after using it because I will use the SP many time in production phase.

[URL]

View 5 Replies View Related

Copy Tabular Structure Into A Temp Table

Feb 17, 2006

Hello Room,
M stuck with an issue with SQL Query. My requirement is to create a temporary table with the out put of "SELECT" Clause..........

Like.......
SELECT NC_ID, AUD_PLAN_ID, AUD_CLAUSE_ID FROM AUD_NC

This is my "Select" Query and all I want is to store the out put in a #table. Now one way is to craete #tmp_table with the fields same as the out put column of the "SELECT" Clause......... But I want it in direct fashion.... dat means without Creating the #tmp_table directly...........

I tried with "CREATE TBALE #tmp_table AS SELECT NC_ID, AUD_PLAN_ID, AUD_CLAUSE_ID FROM AUD_NC".......... But it dini work

Please help me out in this regard......

View 2 Replies View Related

Transact SQL :: Getting Data From External Assembly Into Temp Table Inside Stored Procedure

Oct 8, 2015

I have a Custom .net assembly which retrieves some data, basically just a set of data containing, ID, value,

I need my stored procedure to return this data as a table.

My question what/how is fastest way to do this, my assembly can return anything you want, a datatable, a hashtable, list of(class) etc..

View 3 Replies View Related

Analysis :: Temp Table Like Structure In MDX To Process Intermediate Result

Aug 5, 2015

I have started working on SSAS since last week, I need to perform some calculations on the data fetched from the cube based on the parameters. SSRS is used to display the output and SSAS is used as a data source.

How i could perform the operations on the data fetched from the cube in SSAS? Does SSAS provides the storage structure like temp table in stored procedure where we can perform the various operations before sending final data back to the client side tool(SSRS)?

OR Is there any alternative way to perform the operations based on the input provided through the parameters

View 6 Replies View Related

Inserting Into Temp Table..

Mar 10, 2006

Hi,
I have a proc, if i run that proc from query analyzer it completes in 12 sec.
I want those results to be inserted into temp table. When i try to insert the results from Stored proc to temp table it is taking 5 min.

What could be the cause of the problem?
Any help would be greately appreciated.
sskris

View 4 Replies View Related

Transact SQL :: Inserting Records Into Table 2 From Table 1 To Avoid Duplicates

Nov 2, 2015

INSERT
INTO [Table2Distinct]        
([CLAIM_NUMBER]        
,[ACCIDENT_DATE]

[code]....

I used the above query and it still inserts all the duplicate records. What is wrong with my statement?

View 5 Replies View Related

Inserting Into Temp Table In Dynamic Sql

Mar 3, 2004

I have a temp table in my stored procedure when I try to insert into the temp table thro dynamic sql, it says that table has to be defined. What could be the problem. i have added the code below

CREATE PROCEDURE USP_RULE
AS
declare @TABLE1 table
(
SlNo int identity(1,1), EqNum varchar(25),Pointnum varchar(25)
)
declare @EqNum varchar(25),@Pointnum varchar(25)
DECLARE @STRDBNAME VARCHAR(50)
SET @STRDBNAME = 'DB1'
EXEC('insert into '+@TABLE1+' select EQNUM,POINTNUM from '+@STRDBNAME+'..TABLE2')

GO

View 4 Replies View Related

Inserting Nulls Into A Temp Table

Mar 3, 2008

I'm trying to insert any null values into a temp table. I'm storing the ixo_rlt_code as OldRole, and 'Other' as NewRole. I need both the ixo_rlt_code as OldRole and 'Other' as NewRole in the temp talbe in order to run an update I'm writing.

I know a case statement isn't necessary here, but this section is only one small part of a larger script, so I just used it to be consistent, and it will be easier to make any future changes this way. Below is my code and the error message I'm getting...


select
ixo_key,
ixo_title as Title,
ixo_rlt_code as OldRole,
CASEWHEN ixo_title is null
or ixo_title = ''
or ixo_title = ' '
or ixo_title = ' ' THEN 'Other'

END as NewRole


from
co_customer (nolock)
join co_individual_x_organization (nolock) on ixo_key = cst_ixo_key --and ixo_delete_flag = 0
where
cst_delete_flag = 0
and cst_type = 'Individual'
and ixo_rlt_code is null


This is the Error Message I get:
Server: Msg 515, Level 16, State 2, Line 1095
Cannot insert the value NULL into column 'NewRole', table 'tempdb.dbo.#temp_______________________________________________________________________________________________________________00000001698C'; column does not allow nulls. INSERT fails.
The statement has been terminated.


Thanks ahead of time for any help/suggestions

View 3 Replies View Related

Intermittent Timeout When Inserting Into Temp Table

Sep 27, 2001

I have an ASP page that opens a recordset on a stored procedure. I've had it
in production for over a year, and it usually works fine - subsecond
response. However, in the past couple weeks, the recordset open command has
intermittently started to return timeout errors. It's very strange: when the
timeout occurs, it can be dependably reproduced by opening the ASP page with
the same parameter that produced the initial timeout. However, if you pass a
different parameter to the procedure, it runs fine! It only times out when
using the specific parameter that produced the initial timeout.

Even stranger: If, when attempting to debug it, I use QA to run the sp with
the "defective" parameter, the sp invariably runs fine! And subsequent runs
of the ASP page start working as well!

I have repeated this process many times in the past couple weeks: receive a
report of the timeout error; open the asp page with the parameter that
produced the timeout to verify; repeat; open the asp page with a different
parameter - works fine; repeat with the initial parameter - timeout; Open QA
and run the sp - no problem; refresh the asp page - no more symptom.

The connection to the SQL Server (7.0) uses a specific SQL login for all
communications with the server. So all asp pages are logged in under the
same name. I thought this might be a connection pooliing issue, so this
morning, when the problem occurred, I logged into QA as the special name,
but again, there was no problem running the sp from QA.

So - I've run SQL Profiler to track what's going on when the problem occurs
and I've discovered the last statement to successfully run. Here is the sp:

/*
* File Name: np_GetAvailablePreviews.sql

Returns a list of "reports" available to be previewed, defined as:

date/shift combination with "P" mode and "C" status (if there
are Shift records, there must be an All record)

If none exist, check for the existence of accepted (mode = "A")
Shift records without a corresponding All record - if so, return
an All item for that date

Concatenate <OPTION> tags around each item
*/

CREATE PROCEDURE np_GetAvailablePreviews
(
@DivisionNumber smallint)
AS
BEGIN
set nocount on
declare @count int,
@datefrom datetime
select @datefrom = dateadd(day,-900,getdate())
CREATE TABLE #PreviewReports
(
ProductionDate datetime NULL,
Shift char(3) NULL
)

Insert #PreviewReports
SELECT DISTINCT ProductionDate,Shift
FROM dbo.LineItems
WHERE DivisionNumber = @DivisionNumber
AND Mode = 'P' AND Status = 'C'
AND productiondate >= @datefrom

-->>>The above command completes successfully according to Profiler

Insert #PreviewReports
SELECT distinct t1.ProductionDate, 'All'
FROM
(SELECT distinct ProductionDate, Shift, Mode, Status
FROM LineItems
WHERE DivisionNumber = @DivisionNumber
AND Shift<>'All' AND Mode='A' AND Status='C'
AND productiondate >= @datefrom AND timeperiod IN
('Day','Shift')
) t1
LEFT JOIN
(SELECT distinct ProductionDate, Shift, Mode, Status
FROM LineItems
WHERE DivisionNumber = @DivisionNumber
AND Shift='All' AND Mode='A' AND Status='C'
AND productiondate >= @datefrom AND timeperiod IN
('Day','Shift')
) t2
ON t1.ProductionDate = t2.ProductionDate
WHERE t2.ProductionDate Is Null
AND NOT EXISTS (Select * from #PreviewReports
where productiondate = t1.ProductionDate
and Shift = 'All')

-->>>This one (the one before this comment) starts, but does
not -->>>complete

set @count=(Select Count(*) From #PreviewReports)

-->>This one never begins - the ADO command times out

<snipped>

I did not provide a repro script because the problem is so intermittent that
I doubted it would do anyone any good.

However if someone feels they want to try to reproduce this, I will attempt
to create a repro script for them.

I suspect there is an issue with the temp table, but it's such a moving
target that I haven't been able to pin it down.

Does anyone have any suggestions?

TIA,
Bob Barrows

View 1 Replies View Related

T-SQL (SS2K8) :: Inserting FK Information Into Temp Table

Jan 7, 2015

I need to insert FK information into a temp table using database name and table name as a parameter.

I've been trying different ways, even with global temp table, but still doesn't work. Below is the code showing what I am trying to achieve. I want to avoid global temp table if possible.

IF OBJECT_ID('tempdb..##FKs') IS NOT NULL DROP TABLE ##FKs
CREATE TABLE ##FKs (
[ForeginKeyName] [nvarchar](128) NULL,
[TableSchema] [sysname] NULL,
[TableName] [nvarchar](128) NULL,
[RelatedTableSchema] [sysname] NULL,

[Code] .....

View 9 Replies View Related

Inserting Results From Query Into New Temp Table

Sep 17, 2013

I am try to insert the results from the query into new temp table but keep geeting an error for Incorrect syntax near ')'.

select * into tempCosting
from
(
select top 10* from itemCode itm
where itm.type= 1
)

View 3 Replies View Related

Inserting Few Recordsets Into Temp Table Containing NULL Values

Jul 20, 2005

HiI need some help on achieving the following:I wrote a querie which collects Data out of three Tables, the Resultlooks like this:SET NOCOUNT ONDECLARE @ROWINTDECLARE @CURPTNO CURSORSET @CURPTNO = CURSORFORSELECT * FROM TEMPOPEN @CURPTNOFETCH NEXT FROM @CURPTNOINTO @ROWWHILE (@@FETCH_STATUS = 0)BEGINSELECT ONE.CYNO, ONE.ROLE, ONE.ROL_BEZ, ONE.PTNO, ONE.NOCY, TWO.TEXTAS NOCY_TEXTFROM(SELECT CY.CYNO,RE.CYNO AS RECYNO, RTRIM(RE.ROLE) AS ROLE, RTRIM(V_ROLE.TEXT) ASROL_BEZ,RE.PTNO AS PTNO, RTRIM(RE.NAME) AS SACHBEARBEITER, RE.NOCYFROM CYRIGHT OUTER JOINRE ON RE.CYNO = CY.CYNOINNER JOINV_ROLE ON RE.ROLE = V_ROLE.CODEWHERE (RE.PTNO IN(SELECT PT.PTNOFROM PTWHERE PT.PTNO IN(@ROW)AND V_ROLE.LANGUAGE = PT.CLANG))) AS ONELEFT JOIN(SELECT V_NOCY.CODE, V_NOCY.TEXTFROM V_NOCYINNER JOINPT ON PT.CLANG = V_NOCY.LANGUAGEAND PT.PTNO IN (SELECT PT.PTNOFROM PTWHERE PT.PTNO IN(@ROW))) AS TWOON ONE.NOCY = TWO.CODEFETCH NEXT FROM @CURPTNOINTO @ROWENDCLOSE @CURPTNODEALLOCATE @CURPTNOThe Result looks like this:RS1:6313,1300,Architekt,99737505,NULL,NULL2392762,100,Bauherr,99737505,NULL,NULLRS2:2693265,100,Bauherr,99756900,NULL,NULLNULL,1,Planer,99756900,2,Bauherr macht Pläne selberRS3:2691919,100,Bauherr,99755058,NULL,NULL2691962,6000,Kontakt,99755058,NULL,NULLMy Problem is, that I need to have all the Resultsets in one Table atthe end.So my further undertaking was to create a Temp Table with theexpectation to receive all the resultsets in one Step.The TSQL for this looks like that:SET NOCOUNT ONCREATE TABLE #CYRE_TEMP(CYNOINT NULL,ROLEINT NULL,ROL_BEZVARCHAR (60) NULL,PTNOINT NULL ,NOCYINT NULL,TEXTVARCHAR (60) NULL)GODECLARE @CYNOINT,@ROLEINT,@ROL_BEZVARCHAR (60),@PTNOINT,@NOCYINT,@TEXTVARCHAR (60),@ROWINT,@CURPTNOCURSORSET @CURPTNO = CURSOR FORSELECT PTNO FROM TEMPOPEN @CURPTNOFETCH NEXT FROM @CURPTNOINTO @ROWWHILE (@@FETCH_STATUS = 0)BEGININSERT INTO #CYRE_TEMP (CYNO, ROLE, ROL_BEZ, PTNO, NOCY, TEXT)VALUES(@CYNO,@ROLE ,@ROL_BEZ ,@PTNO ,@NOCY ,@TEXT)SELECT @CYNO = ONE.CYNO,@ROLE = ONE.ROLE,@ROL_BEZ = ONE.ROL_BEZ,@PTNO = ONE.PTNO,@NOCY = ONE.NOCY,@TEXT = TWO.TEXTFROM(SELECT CY.CYNO, RTRIM(RE.ROLE) AS ROLE, RTRIM(V_ROLE.TEXT) ASROL_BEZ,RE.PTNO AS PTNO, RTRIM(RE.NAME) AS SACHBEARBEITER, RE.NOCYFROM CYRIGHT OUTER JOINRE ON RE.CYNO = CY.CYNOINNER JOINV_ROLE ON RE.ROLE = V_ROLE.CODEWHERE (RE.PTNO IN(SELECT PT.PTNOFROM PTWHERE PT.PTNO =@ROWAND V_ROLE.LANGUAGE = PT.CLANG))) AS ONELEFT JOIN(SELECT V_NOCY.CODE, V_NOCY.TEXTFROM V_NOCYINNER JOINPT ON PT.CLANG = V_NOCY.LANGUAGEAND PT.PTNO IN (SELECT PT.PTNOFROM PTWHERE PT.PTNO =@ROW)) AS TWOON ONE.NOCY = TWO.CODEFETCH NEXT FROM @CURPTNOINTO @ROWENDCLOSE @CURPTNODEALLOCATE @CURPTNOSELECT * FROM #CYRE_TEMPDROP TABLE #CYRE_TEMPGOAnd the Output looks like this now:Q1:NULL,NULL,NULL,NULL,NULL,NULL2392762,100,Bauherr,99737505,NULL,NULLNULL,1,Planer,99756900,2,Bauherr macht Pläne selberCan someone help me getting all the 6 Rows into one Table as Output?I appreciate any available Help on this..Ssscha

View 1 Replies View Related

Transact SQL :: Inserting Into Table And Joining With Same Table

Jun 4, 2015

I am looking for an alternate logic for below-mentioned code where I am inserting into a table and having left join with the same table

insert TABLE1([ID],[Key],[Return])
select distinct a.[ID],cat1,cat2 from
(select ID,[Key] Cat1 ,[Return] cat2 from @temp as temp) a left join TABLE1 oon a.ID= o.ID
and a.Cat1 = o.[Key]
and a.cat2 = o.[return]
where [key] is null order by ID

View 2 Replies View Related

Transact SQL :: Cannot Change Table Structure

Oct 5, 2015

I have a simple query which is taking about 2.5 minutes to execute. What can be done to speed it up ? I cannot change the table structure. even without the group by, and without the float and division, it takes about 2.25 minutes.

Select 'SV00302' as FileSource,
[Service_Call_ID],
sum(0) as ActualHours,
sum(cast([Estimate_Hours] as float)/100) as EstHours,
max(MODIFDT+Modified_Time) as ModifiedDateTime

[code]...

View 8 Replies View Related

Inserting Rows Into A Temp Table Created By An Execute Statement

Dec 16, 2007

Below is a simplified table & dataset to illustrate a problem I'm experiencing with a more complex one.





Code Block

create table #test(
recno smallint PRIMARY KEY,
value decimal (18,2))

insert into #test values (1, 3.57)
insert into #test values (2, 5.32)
insert into #test values (3,6.29)
insert into #test values (4, 9.25)
insert into #test values (5, 0.84)

Method 1: I tried inserting rows from #test into a temp table (#table) as follows




Code Block

declare @n as nvarchar(3)
set @n = 1
while @n <= (select count(recno) from #test)
begin
exec ('
insert into ##table
select *,
originalrecno = (select recno from #test where recno = '+@n+')
from #test'
)
set @n = @n + 1
end
However, this yields an error message:




Code Block

Server: Msg 208, Level 16, State 1, Line 2
Invalid object name '##table'.
Note - you can comment out the insert into ##table line above to view the results that I'm trying to put into ##table.


Method 2: next I tried explicitly creating ##table & rerunning the loop containing the insert




Code Block

create table ##table (
recno smallint,
value decimal (18,2),
originalrecno smallint)

declare @n as nvarchar(3)
set @n = 1
while @n <= (select count(recno) from #test)
begin
exec ('
insert into ##table
select *,
originalrecno = (select recno from #test where recno = '+@n+')
from #test'
)
set @n = @n + 1
end
This worked - it inserted the data from the select statements in the loop into ##table.

Question - why won't method 1 work?

View 6 Replies View Related

Trigger Error When Inserting Stored Proc Output Into Temp Table.

Feb 18, 2008





I writing a unit test which has one stored proc calling data from another stored proc. Each time I run dbo.ut_wbTestxxxxReturns_EntityTest I get a severe uncatchable error...most common cause is a trigger error. I have checked and rechecked the columns in both of the temp tables created. Any ideas as to why the error is occurring?

--Table being called.


ALTER PROCEDURE dbo.wbGetxxxxxUserReturns

@nxxxxtyId smallint,

@sxxxxxxxxUser varchar(32),

@sxxxxName varchar(32)

AS

SET NOCOUNT ON




CREATE TABLE #Scorecard_Returns

(
NAME_COL varchar(64),
ACCT_ID int,

ACCT_NUMBER varchar(10),

ENTITY_ID smallint,

NAME varchar(100),

ID int,

NUM_ACCOUNT int,

A_OFFICER varchar(30),

I_OFFICER varchar(30),

B_CODE varchar(30),

I_OBJ varchar(03),

LAST_MONTH real,

LAST_3MONTHS real,

IS int

)




ALTER PROCEDURE dbo.ut_wbTestxxxxReturns_EntityTest



AS

SET NOCOUNT ON




CREATE TABLE #Scorecard_Returns

(
NAME_COL varchar(64),
ACCT_ID int,

ACCT_NUMBER varchar(10),

ENTITY_ID smallint,

NAME varchar(100),

ID int,

NUM_ACCOUNT int,

A_OFFICER varchar(30),

I_OFFICER varchar(30),

B_CODE varchar(30),

I_OBJ varchar(03),

LAST_MONTH real,

LAST_3MONTHS real,

IS int

)

INSERT #Scorecard_Returns(

NAME_COL ,

ACCT_ID

ACCT_NUMBER ,

ENTITY_ID,

NAME,

ID,

NUM_ACCOUNT,

A_OFFICER,

I_OFFICER,

B_CODE,

I_OBJ ,

LAST_MONTH

LAST_3MONTHS,

IS

)

EXEC ISI_WEB_DATA.dbo.wbGetxxxxxcardUserReturns

@nId = 1,

@sSUser = 'SELECTED USER',

@sUName = 'VALID USER'

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

SQL Tools :: Adding Column To A Table Causes Copying Data Into Temp Table

Sep 23, 2015

If on the source I have a new column, the script generated by SqlPackage.exe recreates the table on the background with moving the data into a temp storage. If the table is big, such approach can cause issues.

Example of the script is below: in the source project I added columns [MyColumn_LINE_1]  and [MyColumn_LINE_5].

Is there any way I can make it generating an alter statement instead?

BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [dbo].[tmp_ms_xx_MyTable] (
[MyColumn_TYPE_CODE] CHAR (3) NOT NULL,

[Code] ....

The same script is generated regardless the table having data or not, having a clustered or nonclustered PK.

View 7 Replies View Related

Transact SQL :: Change Structure Of User Defined Table Types

Nov 4, 2015

Change structure of a User Defined Table Types

      field
([idConteudo] [int]
NULL)      to     
 ([idConteudo] [BigInt]
NULL)

Or really should drop and create again?

CREATE TYPE [dbo].[tbProjeto] AS TABLE(
[dsConteudo] [varchar](64) NOT NULL,
[idConteudo] [int] NULL,
[dtConteudo] [datetime] NULL DEFAULT (getdate())
)
GO

View 4 Replies View Related

Inserting Data Into Two Tables (Getting ID From Table 1 And Inserting Into Table 2)

Oct 10, 2007

I am trying to insert data into two different tables. I will insert into Table 2 based on an id I get from the Select Statement from Table1.
 Insert Table1(Title,Description,Link,Whatever)Values(@title,@description,@link,@Whatever)Select WhateverID from Table1 Where Description = @DescriptionInsert into Table2(CategoryID,WhateverID)Values(@CategoryID,@WhateverID)
 This statement is not working. What should I do? Should I use a stored procedure?? I am writing in C#. Can someone please help!!

View 3 Replies View Related

Transact SQL :: Temp Table Scope On Error

Oct 12, 2015

In my sp I'm have an Insert statement. In the event that after the insert @@rowcount = 0 I'm throwing an error with RAISEERROR.

This is fine, however, in my CATCH block I'm referencing a local temp table but getting an error that it no longer exists.

My question is, does throwing an error drop any #temp tables? I thought they were in scope for the session?

View 4 Replies View Related

Transact SQL :: Drop A Temp Table If It Exists?

Jan 21, 2010

What is the best way to drop a temp table if it exists? I am looking something similar to this: if exists (select top 1 * from #TableName) then drop #TableName else end

View 5 Replies View Related

Transact SQL :: Select Values From Temp Table

Jul 10, 2015

DECLARE @Query varchar(8000)
Create Table
#tempCountRichard (Status varchar(50), Number Varchar(1000)
Set @Query = 'Insert Into #tempCountRichard
Select Count(Status),

[code]...

With the following SQL. When I select from the temp table I return the right count but my second column doesn't return anything.

Count Status
1010 2000
1111 2222

When I run the query that is being inserted into the the temp table I return the correct results

Count Status
1010 Pass
2000 Pass with Obs
1111 Fail
2222 None

how to select the data from the temp table exactly the same way it was inserted. As I need to select the exact same data from the insert.

View 23 Replies View Related

Copying Temp Table Data To Permanent Table

Nov 23, 2007

Hello guys..

Can u plz help me by giving me an idea how i can copy the temp table data to permanent table

Thanks,
sohails

View 1 Replies View Related

Rename Table After Loading Data Into Temp Table

Dec 19, 2007

WE have a job that loads data from an Oralce DB into our SQL Server 2000 DB twice a day. The schedule has just changed so that now there is a possibility of having my west coast users impacted when it runs at 5 PM PST and my east coast users impacted when it runs at 7 AM EST. As a workaround, I have developed a DTS package that loads the data into temp tables instead of the real tables. IE. Oracle -> XTable_temp instead of Oracle -> XTable. The load sometimes takes about an hour to an hour and a half to load, so this solution works great, but I want to then lock the table, delete it and rename the temp table to table X. The pseudo code would be:

Begin Transaction


Lock Table XTable

Drop XTable

Alter Table XTable_temp rename to XTable

Release Lock XTable

End Transaction

Create XTable_temp

I see two issues with this solution. 1) I think if I can lock XTable that the lock would be released when the table is dropped and the XTable_temp was being renamed. 2) I can't find a command to rename a table.

Any ideas on a process that might help?


TIA,

A

View 5 Replies View Related

SQL Server 2008 :: Inserting Data From Staging Table To Main Table

Feb 23, 2015

I am trying to insert bulk data into main table from staging table in sql server 2012. If any error comes, this total activity is rollbacked. I don't want that to happen. I want to know the records where ever the problem persists, and the rest has to be inserted.

View 2 Replies View Related

Inserting Distinct Data From One Table In Another Table, How?!?Really Urgent And Needing Help!!!

May 24, 2007

 Hi, I have a table in which I will insert several redundant data. Don't ask why, is Integration services, it only reads data and inserts it in a SQL table. THis way, I have a SQL table with several lines repeating them selves. What I want to do is create a procedure that reads the distinct data and inserts it in another table, but my problem is that I am not able to select data line by line on the original table to save it in local variables and insert it on the another table, I just can select the last line. I've tried a while cycle but no succeed. Here is my code: create proc insertLocalizationASdeclare @idAp int, @macAp varchar(20), @floorAp varchar(2), @building varchar(30), @department varchar(30)select @idAp = idAp from OLTPLocalization where idAp not in (select idAp from dimLocalization)select @macAp=macAp,@floorAp=floorAp,@building=building,@department=department from OLTPLocalizationif (@idAp <> null)beginInsert into dimLocalization VALUES(@idAp,@macAp,@floorAp,@building,@department)endGO This only inserts the last line in the "oltpLocalization" table. O the other hand, like this:create proc aaaaasdeclare @idAp as int, @macAp as varchar(50), @floorAp as int, @building as varchar(50), @department as varchar(50)while exists (select distinct(idAp) from OLTPLocalization)begin    select @idAp =idAp from OLTPLocalization  where idAp not in (select idAp from dimLocalization)    select @macAp = macAp from OLTPLocalization where idAp = @idAp    select @building = building from OLTPLocalization where idAp = @idAp    select @department = department from OLTPLocalization where idAP = @idApif (@idAp <> null)begin    insert into dimLocalization values(@idAp,@macAp,@floorAp,@building,@department)endendgo this retrieves every distinct idAp in each increment on the while statement. The interess of the while is really selecting each different line in the OLTPLocalization table. I did not find any foreach or for each statement, is there any way to select distinct line by line in a sql table and save each column result in variables, to then insert them in another table? I've also thought about web service, that reads the distinct data from the oltpLocalization into a dataset, and then inserts this data into the dimLocalization table. Is there anything I can do?Any guess?Really needing a hand here!Thanks a lot!

View 1 Replies View Related







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