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


ADVERTISEMENT

I Have Created A Table Table With Name As Varchar And Id As Int. Now I Have Started Inserting The Rows Like, Insert Into Table Values ('arun',20).

Jan 31, 2008

I have created a table Table with name as Varchar and id as int. Now i have started inserting the rows like, insert into Table values ('arun',20).Yes i have inserted a row in the table. Now i have got the values " arun's ", 50.                 insert into Table values('arun's',20)  My sqlserver is giving me an error instead of inserting the row. How will you solve this problem? 
 

View 3 Replies View Related

Temp Table Created In The SSMS,but SSRS Gives Error

Feb 8, 2008

Hi ALL,
The sub report has stored procedure which uses ##temp table,to get it's results.
Stored procedure code is:


set ANSI_NULLS ON

set QUOTED_IDENTIFIER OFF

GO

ALTER PROCEDURE [dbo].[rpt_FAP_Profile_claim] @TABLE_NM varchar(50),@MBR_ID varchar(50)

AS

SET NOCOUNT ON

DECLARE @SQL_TXT varchar(8000)



SET @SQL_TXT = ' SELECT * FROM STEP_PROFILE_CLAIM_' + @TABLE_NM + ' c WHERE c.MBR_ID = '''+ @MBR_ID + ''''

--SET @SQL_TXT = 'SELECT TOP 100 * FROM CLAIM'

EXEC(@SQL_TXT)

When I run this in SSMS gives error::-

Msg 208, Level 16, State 1, Line 1

Invalid object name 'STEP_PROFILE_CLAIM_765032'.

(1 row(s) affected)

How do I make it work and get the result in my sub report.Is any properties needs to be set in the SSMS or SSRS sub report or any other modificatons?.Or is some thing wrong in the temp table?.Plz help.
Thanks in advance.

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

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

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

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

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 :: Table Trigger To Delete All Rows Before Inserting Rows

Jul 24, 2015

I have a SQL script to insert data into a table as below:

INSERT into [SRV1INS2].BB.dbo.Agents2
select * from [SRV2INS14].DD.dbo.Agents

I just want to set a Trigger on Agents2 Table, which could delete all rows in the table , before carry out any Insert operation using above statement.I had below Table Trigger on [SRV1INS2].BB.dbo.Agents2 Table as below: But it did not perform what I intend to do.

USE [BB]
GO
/****** Object:  Trigger    Script Date: 24/07/2015 3:41:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[code]....

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

Temp Table In An If Statement

Dec 5, 2007



I have the following code II am using to look at the date are return a result. I want the result to go into a #temp table

each piece of the code works by itself, however when its structured with if statements it fails.

here's the code... any help telling us why it will not create to a temp file is greatly appreciated:


--Months = 1, 2 or 3

if((select DATEPART(month, GETDATE()) AS CurrentMonth)>0 and (select DATEPART(month, GETDATE()) AS CurrentMonth)<=3)

select 'Qtr 4' AS DDLValue

,'m' AS ORDERX

, '10/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '12/31/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate into #temp7

union

select 'Qtr 3' AS DDLValue

,'n' AS ORDERX

, '7/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '9/30/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

union

select 'Qtr 2' AS DDLValue

,'o' AS ORDERX

, '4/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '6/30/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

union

select 'Qtr 1' AS DDLValue

,'p' AS ORDERX

, '1/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '3/31/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

--Months = 4, 5 or 6

if((select DATEPART(month, GETDATE()) AS CurrentMonth)>=4 and (select DATEPART(month, GETDATE()) AS CurrentMonth)<=6)

select 'Qtr 1' AS DDLValue

,'m' AS ORDERX

, '1/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '3/31/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate into #temp7

union

select 'Qtr 4' AS DDLValue

,'n' AS ORDERX

, '10/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '12/31/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

union

select 'Qtr 3' AS DDLValue

,'o' AS ORDERX

, '7/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '9/30/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

union

select 'Qtr 2' AS DDLValue

,'p' AS ORDERX

, '4/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '6/30/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate



--Months = 7,8 or 9

if((select DATEPART(month, GETDATE()) AS CurrentMonth)>6 and (select DATEPART(month, GETDATE()) AS CurrentMonth)<=9)

select 'Qtr 2' AS DDLValue

,'m' AS ORDERX

, '4/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '6/30/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate into #temp7

union

select 'Qtr 1' AS DDLValue

,'n' AS ORDERX

, '1/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '3/31/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate

union

select 'Qtr 4' AS DDLValue

,'o' AS ORDERX

, '10/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '12/31/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

union

select 'Qtr 3' AS DDLValue

,'p' AS ORDERX

, '7/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '9/30/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate



--Months = 10,11,12

if((select DATEPART(month, GETDATE()) AS CurrentMonth)>9 and (select DATEPART(month, GETDATE()) AS CurrentMonth)<=12)

select 'Qtr 3' AS DDLValue

,'m' AS ORDERX

, '7/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '9/30/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate into #temp7

union

select 'Qtr 2' AS DDLValue

,'n' AS ORDERX

, '4/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '6/30/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate

union

select 'Qtr 1' AS DDLValue

,'o' AS ORDERX

, '1/1/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS StartDate

, '3/31/' + convert(varchar(10),DATEPART(year, GETDATE()), 101) AS EndDate

union

select 'Qtr 4' AS DDLValue

,'p' AS ORDERX

, '10/1/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS StartDate

, '12/31/' + convert(varchar(10),DATEPART(year, GETDATE()) - 1, 101) AS EndDate

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

Transact SQL :: Login Name Of User Inserting Into Table With Execute As DML Trigger?

Jun 24, 2015

Suppose you have a simple DML "execute as..." trigger that looks like this:

CREATE TRIGGER dbo.myTrigger
 ON dbo.myTable
 WITH Execute As Owner
 AFTER INSERT
AS

[code]...

which runs as "owner" so that the user inserting into "myTable" won't have the privs to edit the audit table.How does one capture the identity of the user whose insert statement caused the trigger to fire?  I've tried "current_user" and "system_user" without success when "execute as ..." is used: they each return a value not related to the identity of the user running the original insert.without an "execute as" clause, what prevents a user from adding to or editing the audit table directly?

View 6 Replies View Related

Trigger On Table LeaveRegister And Inserting Rows In Audit Table

Oct 22, 2012

I write a insert trigger on my table LeaveRegister(1000 rows) and inserting rows in audit table, but when i inserting a row in LeaveRegister table. In audit table 1000 + 1 rows are inserting every time.

View 6 Replies View Related

Transact SQL :: Temp Table - Display Duplicate IDs In Multiple Rows

Jun 30, 2015

I have a temp table with the following columns and data 

drop table #temp
create table #temp (id int,DLR_ID int,KPI_ID int,Brnd_ID int)
insert into #temp values (1,2343,34,2)
insert into #temp values (2,2343,34,2)
insert into #temp values (3,2343,34,2)

[Code]....

I use the rank function on that table and get the following results

select rank() over (order by DLR_ID,KPI_ID,BRND_ID  ) Rown,* from #temp

I am interested only in Rown and Id columns. For each Rown number, I need to get the min(ID) in the second column and the duplicate ID should be in 3rd column as shown below.If i have 3 duplicate IDs , I should have 3 rows with 2nd column being the min(id) and 3rd column having one of the duplicate ids in ascending order(as shown in Rown=6)

View 7 Replies View Related

Calculating Value From Two Separate Rows In The Same Table And Inserting As New Row In The Same Table

Jan 19, 2008

Code Block


Hi,

I'm working on a database for a financial client and part of what i need to do is calculate a value from two separate rows in the same table and insert the result in the same table as a new row. I have a way of doing so but i consider it to be extremely inelegant and i'm hoping there's a better way of doing it. A description of the existing database schema (which i have control over) will help in explaining the problem:

Table Name: metrics_ladder

id security_id metric_id value
1 3 80 125.45
2 3 81 548.45
3 3 82 145.14
4 3 83 123.32
6 4 80 453.75
7 4 81 234.23
8 4 82 675.42
.
.
.

Table Name: metric_details

id metric_id metric_type_id metric_name
1 80 2 Fiscal Enterprise Value Historic Year 1
2 81 2 Fiscal Enterprise Value Current Fiscal Year
3 82 2 Fiscal Enterprise value Forward Fiscal year 1
4 83 2 Fiscal Enterprise Value Forward Fiscal Year 2
5 101 3 Calendar Enterprise value Historic Year 1
6 102 3 Calendar Enterprise Value Current Fiscal Year
5 103 3 Calendar Enterprise value Forward Year 1
6 104 3 Calendar Enterprise Value Forward Year 2

Table Name: metric_type_details

id metric_type_id metric_type_name
1 1 Raw
2 2 Fiscal
3 3 Calendar
4 4 Calculated

The problem scenario is the following: Because a certain number of the securities have a fiscal year end that is different to the calendar end in addition to having fiscal data (such as fiscal enterprise value and fiscal earnings etc...) for each security i also need to store calendarised data. What this means is that if security with security_id = 3 has a fiscal year end of October then using rows with ids = 1, 2, 3 and 4 from the metrics_ladder table i need to calculate metrics with metric_id = 83, 84, 85 and 86 (as described in the metric_details table) and insert the following 4 new records into metrics_ladder:

id security_id metric_id value
1 3 101 <calculated value>
2 3 102 <calculated value>
3 3 103 <calculated value>
4 3 104 <calculated value>

Metric with metric_id = 101 (Calendar Enterprise value Historic Year 1) will be calculated by taking 10/12 of the value for metric_id 80 plus 2/12 of the value for metric_id 81.

Similarly, metric_id 102 will be equal to 10/12 of the value for metric_id 81 plus 2/12 of the value for metric_id 82,

metric_id 103 will be equal to 10/12 of the value for metric_id 82 plus 2/12 of the value for metric_id 83 and finally

metric_id 104 will be NULL (determined by business requirements as there is no data for forward year 3 to use).

As i could think of no better way of doing this (and hence the reason for this thread) I am currently achieving this by pivoting the relevant data from the metrics_ladder so that the required data for each security is in one row, storing the result in a new column then unpivoting again to store the result in the metrics_ladder table. So the above data in nmetrics_ladder becomes:

security_id 80 81 82 83 101 102
----------- -- -- -- -- -- --
3 125.45 548.45 145.14 123.32 <calculated value> <calculated value>
4 ...
.
.
.

which is then unpivoted.

The SQL that achieves this is more or less as follows:

*********
START SQL
*********

declare @calendar_averages table (security_id int, [101] decimal(38,19), [102] decimal(38,19), [103] decimal(38,19), [104] decimal(38,19),etc...)


-- Dummy year variable to make it easier to use MONTH() function
-- to convert 3 letter month to number. i.e. JAN -> 1, DEC -> 12 etc...
DECLARE @DUMMY_YEAR VARCHAR(4)
SET @DUMMY_YEAR = 1900;

with temp(security_id, metric_id, value)
as
(
select ml.security_id, ml.metric_id, ml.value
from metrics_ladder ml
where ml.metric_id in (80,81,82,83,84,85,86,87,88,etc...)
-- only consider securities with fiscal year end not equal to december
and ml.security_id in (select security_id from company_details where fiscal_year_end <> 'dec')
)
insert into @calendar_averages
select temppivot.security_id
-- Net Income
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[80])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[81]) as [101]
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[81])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[82]) as [102]
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[82])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[83]) as [103]
,NULL as [104]
-- Share Holders Equity
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[84])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[85]) as [105]
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[85])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[86]) as [106]
,(CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR))/12*[86])
+((12 - CONVERT(DECIMAL, MONTH(cd.fiscal_year_end + @DUMMY_YEAR)))/12*[87]) as [107]
,NULL as [108]
-- Capex
-- Sales
-- Accounts payable
etc...
..
..
from temp
pivot
(
sum(value)
for metric_id in ([80],[81],[82],[83],[84],[85],[86],[87],[88],etc...)
) as temppivot
inner join company_details cd on temppivot.security_id = cd.security_id

*********
END SQL
*********

The result then needs to be unpivoted and stored in metrics_ladder.

And FINALLY, the question! Is there a more elegant way of achieving this??? I have complete control over the database schema so if creating mapping tables or anything along those lines would help it is possible. Also, is SQL not really suited for such operations and would it therefore be better done in C#/VB.NET.

Many thanks (if you've read this far!)

M.

View 6 Replies View Related

Inserting Rows Into Existing SQL Table

May 21, 2008

Hi all,

I am trying to insert some new rows into an existing SQL table. The table name is Agt_table, and I want to add some data for some new agents into existing columns:
Agent name, agent code, phone number, fax number

Example -
I want to add the following record to my existing table Agt_table
Agent name: ABC Company
Agent code: 012345
Phone #: 555-555-5555
Fax#: 555-555-5555

How would I write the sql statement to do that?

Thanks so much!!!

View 12 Replies View Related

INSERTING MULTIPLE ROWS IN A TABLE

Jun 20, 2007

Hi,

Is it possible to insert multiple rows in a table using one INSERT statment. If yes, how can I do that ? I tried doing this using the substitution method.

Using Substitution Method - This is how,I proceeded.

INSERT INTO EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
SELECT ‘&EMPN’, ‘&ENAM’, ‘&JO’, ‘&MG’, ‘&HI’, ‘&SA’, ‘&COMM’, ‘&DEPTN’ UNION ALL
SELECT ‘&EMPN’, ‘&ENAM’, ‘&JO’, ‘&MG’, ‘&HI’, ‘&SA’, ‘&COMM’, ‘&DEPTN’

Let me know if this is correct.

Thanks,
Vandana

View 2 Replies View Related

Inserting The Diff Rows Into A Table

Sep 24, 2007



Hi,
I have two tables as follows
Table TempTab
{

CatId varchar(20),
lastupdate Datetime
}

Table MainTab
{

CatId varchar(20),
lastupdate Datetime
}
and the data in those tables are as follows


Table TempTab
{

CatId LastUpdate
------------------------------
Cat1 D1
Cat2 D2
Cat3 D3
Cat4 D4
}



Table MainTab
{

CatId LastUpdate
------------------------------
Cat1 D1
Cat3 D3
Cat5 D5
}


I need a query to insert the differences into the MinTab, i mean to say the fincal MainTab should look like as follows
Table MainTab
{

CatId LastUpdate
------------------------------
Cat1 D1
Cat2 D2
Cat3 D3
Cat4 D4
Cat5 D5

}



can any one please let me know the query

Thanks alot
~Mohan

View 3 Replies View Related

Inserting Millions Of Rows Into A Table

Aug 10, 2006

Hi,

I have a DataTable in memory and I want to write a C# code to dump the data into a SQL database. Is there a faster way of dumping millions of rows into a SQL table besides running INSERT INTO row by row?

Thank you,

Jina

View 3 Replies View Related

Transact SQL :: Select 1000 Rows At A Time From / Into A Large Temp Table?

May 12, 2015

I am using SQL SERVER 2008R2, not Denali, so I cannot use OFFSET FETCH Clause.

In my stored procedure, I am doing a SELECT INTO #tblTemp FROM... Working fine. This resultset is going to be used in an SSIS package which will generate a pipe-delimited .txt file... Working fine.

For recoverability sake, I am trying to throttle back on the commit chunks to 1000 rows per commit until there are no more rows. I am trying to avoid large rollbacks.

Q: Am I supposed to handle the transactions (begin/commit/rollback/end trans) when the records are being inserted into the temp table? Or when they are being selected form the temp table?

Q: Or can I handle this in my SSIS package for a flat file destination? I don't see option for a flat file destination like I do for an OLE DB Destination (like Rows per batch, Maximum insert commit size).

View 6 Replies View Related

Problem Inserting Rows After Table Creation

Dec 29, 2004

I am using the below SQL to insert a table. The problem is after I run this, I run another script to populate the table (see below). The population script will work if I run it as INSERT INTO ... SELECT TOP 99.9999999 PERCENT ..., but if I put 100 PERCENT, or just use no percent limiter I get the following error: Msg 8624, Internal SQL Server error.

It is weird b/c once something is inserted in the table, i can run the populate script without any problems. Any idea as to why this is happening?

Thanks,

Dave

TABLE GENERATION SCRIPT

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tbCelebroAds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tbCelebroAds]
GO

CREATE TABLE [dbo].[tbCelebroAds] (
[AdID] [int] IDENTITY (1, 1) NOT NULL ,
[BranchCode] [int] NOT NULL ,
[PropertyID] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[AdScheduleCode] [int] NOT NULL ,
[RecAtCentral] [int] NULL ,
[AdRan] [int] NOT NULL ,
[AdStatusID] [int] NOT NULL ,
[PatID] [int] NULL ,
[RunDate] [datetime] NOT NULL ,
[CreationCost] [float] NOT NULL ,
[BillCost] [float] NOT NULL ,
[AddedDate] [smalldatetime] NOT NULL
) ON [PRIMARY]


TABLE POPULATION SCRIPT

INSERT INTO tbCelebroAds (BranchCode, PropertyID, AdScheduleCode, PatID, AdStatusID, AdRan, RunDate, CreationCost, BillCost, AddedDate)
SELECT [TOP 100 PERCENT or no percent limiter doesn't work, TOP 99.9999999 PERCENT does] BranchCode, PropertyID, AdScheduleCode, cp.PatID, 6, 0, CAST(PubDate AS DATETIME), CAST(ISNULL(pat.Cost,0) AS DECIMAL(10,2)), 0, GetDate()
FROM tbCelebroView cv
LEFT JOIN tbCelebroPubs cp ON cv.PublicationName = cp.PublicationName AND cv.AdSectionName = cp.AdSectionName
LEFT JOIN tbPubToAdType pat ON cp.PatID = pat.PatID
WHERE CAST(BranchCode AS nvarchar(20)) + CAST(PropertyID AS varchar(20)) + CAST(AdScheduleCode AS nvarchar(20)) NOT IN
(SELECT CAST(BranchCode AS nvarchar(20)) + CAST(PropertyID AS varchar(20)) + CAST(AdScheduleCode AS nvarchar(20)) FROM tbCelebroAds)

View 4 Replies View Related

Inserting Multiple Rows Into One Table (with Calculated Fields)

Nov 29, 2006

Hello all,my first post here...hope it goes well. I'm currently working onstored procedure where I translated some reporting language into T-SQLThe logic:I have a group of tables containing important values for calculation.I run various sum calculations on various fields in order to retrievecost calculations ...etc.1) There is a select statement which gathers all the "records" whichneed calculations.ex: select distinct Office from Offices where OfficeDesignation ='WE' or OfficeDesignation = 'BE...etc.As a result I get a list of lets say 5 offices which need to becalculated!2) A calculation select statement is then run on a loop for each ofthe returned 5 offices (@OfficeName cursor used here!) found above.Anexample can be like this(* note that @WriteOff is a variable storing the result):"select @WriteOff = sum(linecost * (-1))From Invtrans , InventoryWhere ( transtype in ('blah', 'blah' , 'blah' ) )and ( storeloc = @OfficeName )and ( Invtrans.linecost <= 0 )and ( Inventory.location = Invtrans.storeloc )and ( Inventory.itemnum = Invtrans.itemnum )"...etcThis sample statement returns a value and is passed to the variable@WriteOff (for each of the 5 offices mentioned in step 1). This is donearound 9 times for each loop! (9 calculations)3) At the end of each loop (or each office), we do an insert statementto a table in the database.


Quote:

View 9 Replies View Related

SQL 2000: Inserting Multiple Rows Into A Single Table

Jul 20, 2005

To anyone that is able to help....What I am trying to do is this. I have two tables (Orders, andOrderDetails), and my question is on the order details. I would liketo set up a stored procedure that essentially inserts in the orderstable the mail order, and then insert multiple orderdetails within thesame transaction. I also need to do this via SQL 2000. Right now ihave "x" amount of variables for all columns in my orders tables, andall Columns in my Order Details table. I.e. @OColumn1, @OColumn2,@OColumn3, @ODColumn1, @ODColumn2, etc... I would like to create astored procedure to insert into Orders, and have that call anotherstored procedure to insert all the Order details associated with thatorder. The only way I can think of doing it is for the program to passme a string of data per column for order details, and parse the stringvia T-SQL. I would like to get away from the String format, and gowith something else. If possible I would like the application tosubmit a single value per variable multiple times. If I do it this waythough it will be running the entire SP again, and again. Anysuggestions on the best way to solve this would be greatlyappreciated. If anyone can come up with a better way feel free. Myonly requirement is that it be done in SQL.Thank you

View 3 Replies View Related

Dynamically Listing Created Temp Tables

Jan 21, 2002

Hi,

I want to create a nested SP which will dump out the results of All Temp Tables that are currently created in the session. The purpose of this is for createing a generic debugging SP which will write the contents of all temp tables to a debug table (when a certain flag is set).

I need to know how to:

- Get a list of all temp tables created
- Get a list from each temp table of the columns created.

Hope someone can help!

Cheers,

Andrew

View 1 Replies View Related

Temp Tables Created In Stored Procedures

Feb 12, 2008

Are they unique to a user/session? Like if 2 users simultaneously run the stored procedure?
TIA!

View 13 Replies View Related

Exporting Data From SQL Table To Excel File - How To Delete Rows Before Inserting New

Feb 5, 2007

Hi,

Question pls. I have an MS SQL local package where it exports data from SQL table to Excel file. My question is, how can erase all the records in my excel file before i export the new data from SQL table?

What i want is to delete the rows in the destination file before inserting new records.

Thanks a lot.

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

Execute A Dts Package From A Newly Created JOB

Feb 17, 2000

I am trying to execute three dts packages from a Job that I created. When creating the steps I am setting the Type To: Operating System Command(CmdExec).

The Command I am using is: dtsrun /S servername /E /dtsPackageName

For some reason whenever I try to run thes jobs it fails. Within this Job I have three steps. For each step I am using the same job but with a different package name. I have a trusted connection so my command should work just fine. What am I doing wrong. Can some please explain this process.

Thanks

View 1 Replies View Related







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