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


ADVERTISEMENT

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

Dec 4, 2015

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

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

Data in permTable
col1   col2
11,    12
21,     22

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

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

What is the syntax for an insert like this?

View 2 Replies View Related

Transact SQL :: 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

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

Transact SQL :: Insert Using Select Intersect / Except - Number Of Supplied Values Not Match Table Definition

May 12, 2015

I have two tables, D and C, whose INTERSECT / EXCEPT values I'd like to insert in the following table I've created

CREATE TABLE DinCMatch (
servername varchar(50),
account_name varchar (50),
date_checked datetime DEFAULT getdate()
)

The following stmt won't work...

INSERT INTO DinCMatch
select servername, account_name from D
intersect
select servername, account_name from C

... as the number of supplied values does not match table definition.

View 2 Replies View Related

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

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

Jun 6, 2005

Hello,

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
TRUNCATE TABLE #tbl_User_Temp

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

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

Thanks,
Greg.

View 2 Replies View Related

Temp Table Values

May 23, 2008

Hello,

I have created a temporary table that has an identity and default values that it creates and sets but also it needs to get values from a sub query for the final insert into the temp table. I have my create temp table, and my insert into set up but my select is confusing me since some of the values I need to select are determined as they are entered into the temp table. Is there a way to alias them or not put them in the select? If I leave them out it says there are more values in the insert than in the select.


Create Table #TempLabTestConfigImport

(temp_id int identity(1,1),system_id int default 2250, labtestkey nvarchar(10) null,

valuecode nvarchar(10)null, value_description nvarchar(50) null,

value_code_system varchar(10) default 'L',value_type char(2) null,

units nvarchar(5) null,sequence_number int null, table_name nvarchar(50) null,

field_name nvarchar(50) null,created_by int default 57,create_timestamp datetime default getdate(),

modified_by int default 57,modify_timestamp datetime default getdate(),

row_timestamp datetime default getdate())

/*CTE and sub query that combines the data for import and inserts it into temp table*/

With labtestcheck (labtestcode)

as

(

select a.labtestcode

from EMR_temp_labtest_configupdate a

Where Not Exists (Select * From lab_test_add_conf b where b.labtest_key = a.labtestcode)

)

Insert Into #TempLabTestConfigImport

(temp_id,system_id,labtestkey,valuecode,value_description,value_code_system,

value_type,units,sequence_number,table_name,field_name,created_by,create_timestamp,modified_by,

modify_timestamp, row_timestamp)

SELECT temp_id,system_id,

l.labtestcode,t.valuecode,t.valuedesc,value_code_system,

t.valuetype,t.units,t.SequenceCount,t.tablename,t.fieldname, created_by,

create_timestamp,modified_by,modify_timestamp, row_timestamp

FROM labtestcheck l

INNER JOIN

(

select t.labtestcode,b.valuecode,b.valuedesc,b.valuetype,b.units,

row_number() over (partition by t.labtestcode order by b.valuecode) as SequenceCount,

b.tablename,b.fieldname

from EMR_temp_labtest_configupdate a

inner join emr_zseg_code_descriptions b on a.zsegcode = b.zsegcode

inner join labtestcheck t on t.labtestcode = a.labtestcode)t

ON t.labtestcode=l.labtestcode

View 2 Replies View Related

Transact SQL :: Update One Table Based On Another Table Values For Multiple Values

Apr 26, 2015

I have two tables  A(uname,address,full_name) and B(uname,full_name). I want to update table A for all matching case of uname in table B. 

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

Rearranging Values In Temp Table

Jul 25, 2004

Hello everyone :)

I have a temp table that looks like this (as a result of two seperate inserts into it):

RowNumber starttime endtime
----------- ----------- -----------
1 l 0 l NULL
2 l 360 l NULL
3 l 720 l NULL
4 l 1020 l NULL
5 l 1380 l NULL
6 l NULL l 180
7 l NULL l 540
8 l NULL l 900
9 l NULL l 1200
10 l NULL l 1440

I need some help getting it to look like this (with No NULL cell values)!

RowNumber starttime endtime
----------- ----------- -----------
1 l 0 l 180
2 l 360 l 540
3 l 720 l 900
4 l 1020 l 1200
5 l 1380 l 1440

PLEASE help I have been looking at this for the past 3 days and can't figure it out! :o

View 6 Replies View Related

Passing Temp Table Values Into A UDF

Jul 20, 2005

This one is interesting...Is there any way to pass a joined parameter into a UDF as I'm attempting below?I have a temp table that I'm trying to create:create table #t3(bmkPerson int primary key,LangCode nchar(5),SName varchar(1000))insert into #t3select t2.bmkPerson, t2.LangCode,select SName from SName_trans_udf(t2.LangCode)from #t2 t2Thanks in advance,RenaeJoin Bytes!

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

Asssigning Values To Multiple Vars In A SP In One Go (without Temp Table)

Feb 22, 2007

I have to select several field values from a table and need to assign them to different variables in my SP.Here's what I do now:
declare @ReceiverEmail nvarchar(50)
SET @ReceiverEmail=(SELECT Email FROM Users WHERE UserCode=@UserCodeOwner)
declare @UsernameSender nvarchar(50)
SET @UsernameSender=(SELECT Username FROM Users WHERE UserCode=@UserCodeOwner)As you can see I have to search the Users table twice: once for the Email and a second time for the Username...and all that based on the SAME usercode...:SSo, is there an option where I only have to search the table once and return the Email and UserName fields and assign them to my variables (without using a temp table....)?

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 :: How To Do Bulk Insert Into Temp Table From Text File

Sep 15, 2015

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

My statement looks like this:

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

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

View 2 Replies View Related

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

Transact SQL :: Create A Temp Table On Results Of A Pivot Query?

Jun 17, 2015

I pulled some examples of using a subquery pivot to build a temp table, but cannot get it to work.

IF OBJECT_ID('tempdb..#Pyr') IS NOT NULL
DROP TABLE #Pyr
GO
SELECT
vst_int_id,
[4981] AS Primary_Ins,
[4978] AS Secondary_Ins,

[code]....

The problems I am having are with the integer data being used to create temp table fields. The bracketed numbers on line 7-10 give me an invalid column name error each. In the 'FOR', I get another error "Incorrect syntax near 'FOR'. Expecting '(', or '.'.".   The first integer in the "IN" gives me an "Incorrect syntax near '[4981]'. Expecting '(' or SELECT".  I will post the definitions from another effort below.

CREATE TABLE #Pyr
(
vst_int_idINTEGERNOT NULL,
--ivo_int_idINTEGERNOT NULL,
--cur_pln_int_idINTEGERNULL,
--pyr_seq_noINTEGERNULL,

[code]....

SQL Server 2008 R2.

View 3 Replies View Related

Transact SQL :: How To Store Result Of Exec Command Into Temp Table

Apr 7, 2013

I wanted to insert the result-set of a Exec(@sqlcommand) into a temp table. I can do that by using:

Insert into #temp
Exec(@sqlcommand)

For this to accomplish we need to define the table structure in advance. But am preparing a dynamic-sql command and storing that in variable @sqlcommand and the output changes for each query execution. So my question is how to insert/capture the result-set of Exec(@sqlcommand) into a temp table when we don't know the table structure.

View 17 Replies View Related

Transact SQL :: Create Temp Table That Persists While A Front End App Is Open

Sep 30, 2015

I have an Access app. that I am migrating the DB portion (queries, tables) to SQL server. I need to create a temp table that lasts as long as the user has the Access FE app. open. Idea is that the temp table stores the user's parameters (used for filtering data entry forms and report). The parameters allow the app. to only show the user his data (cannot view other users data). The SP shown below works OK, it creates a ##Temp table and updates it with the parameters sent by Access FE app. The issue I am having is that as soon as the SP finishes the ##Temp table is removed. I thought of using a regular table, but, I am currently testing this migration in my local SQL server instance, as soon as I move the database to production environment, then users will not be able to create tables as permissions are only read/write.

USE [Work_Allocation]
GO
/****** Object: StoredProcedure [dbo].[spUser_Parameters_update] Script Date: 9/30/2015 12:27:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUser_Parameters_update]

[code]...

View 10 Replies View Related

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

Jul 21, 2015

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

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

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

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

[Code] ....

View 3 Replies View Related

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

Dec 28, 2006

Hi,
I am using a SQL back end to dynamically populate an asp.net 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.
Thanks.
John

View 2 Replies View Related

T-SQL (SS2K8) :: Load Values From Stored Procedure Into A Temp Table?

May 8, 2014

I would like to know if the following sql can be used to obtain specific columns from calling a stored procedure with parameters:

/* Create TempTable */
CREATE TABLE #tempTable (MyDate SMALLDATETIME, IntValue INT)
GO
/* Run SP and Insert Value in TempTable */
INSERT INTO #tempTable (MyDate, IntValue)
EXEC TestSP @parm1, @parm2

If the above does not work or there is a better way to accomplish this goal, how to change the sql?

View 1 Replies View Related

SELECT INTO TEMP TABLE

Apr 17, 2007

The following batch does not compile. It works for real tables but not temp tables. I need to get this to work. Any ideas? Thanks.

code
-------------------
IF 1 = 1 --IF CONDITION
BEGIN
SELECT * INTO #TEMP FROM TABLE1
END
ELSE
BEGIN
SELECT * INTO #TEMP FROM TABLE2
END
--------------------
Error Msg
Msg 2714, Level 16, State 1, Line 7
There is already an object named '#TEMP' in the database.
--------------------

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

Select Data From #temp Table In SQL

Apr 6, 2004

I am building a dynamic query stored procedure. I am first filling a temp table with data:

Declare
@Counter int

drop table #tempmerge
create table #tempmerge(IDIndex int IDENTITY, CitationNum char(9),Exp1 int)

insert into #tempmerge
Select E_Cit_For_Merge, Count(*) as Exp1
from dbo.E_Citation_XML_Data
group by E_Cit_For_Merge
having Count(*)>1
select * from #tempmerge

Results returned from #tempmerge table:

IDIndex CitationNum Exp1
----------- ----------- -----------
1 4AA020621 2
2 4AA022361 2
3 4AA022391 2
4 4AA022423 2
5 4AA022532 3
6 4AA027761 2
7 4AA030513 2

Then, I want to use a while loop, looping thru the #tempmerge table
and retrieving the CitationNum value of each row:

set @RowCount = (Select Count(*) from #tempmerge)
set @Counter = 1
While @Counter <= @RowCount
Begin

Set @WhereStatement2 = ' where E_Cit_For_Merge= (Select CitationNum from #tempmerge
where IDIndex = @Counter)'

E_Cit_For_Merge is a field in a SQL table.
I Declare @Counter as int.

I get the Error message that:

FROM E_Citation_XML_Data where E_Cit_For_Merge= (Select CitationNum from #tempmerge
where IDIndex = @Counter)

Server: Msg 137, Level 15, State 2, Line 24
Must declare the variable '@Counter'.

Any Suggestions?
Thanks
JEB

View 6 Replies View Related

Temp Table Or Nested Select

Jan 30, 2007

hi all,
i have speed issue on displaying 4k line of records using temp table.. before this it works fine and fast.. but maybe when i starts joining group by it loads slower.

SELECT DISTINCT customlotno, itemid, ItemName, Ownership, TotalCTNInPlt, TotalCarton, sum(CartonPcs) AS CartonPcs, StorageID, StorageStatus ,OriginUOM, PickQtyUOM, WhsID, WhsName, LocID, Zone, Expirydate, recvDate
INTO #ByItemID
FROM (
SELECT * FROM tblItemdetail
)AS L1
GROUP BY customlotno, itemid, ItemName, ownership, TotalCTNInPlt, TotalCarton, StorageID, StorageStatus ,OriginUOM, PickQtyUOM, WhsID, WhsName, LocID, Zone, Expirydate, recvDate

SELECT *
FROM #ByItemID
ORDER BY CustomLotNo

DROP TABLE #ByItemID

----------------------------
or maybe just use something like nested SELECT like this, but cannot work:-

select customlotno, itemid, locid(

select * from tblitemdetail
where customlotno='IN28606000'

) AS T
GROUP BY customlotno, itemid, locid


~~~Focus on problem, not solution~~~

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

Transact SQL :: Create Index On Temp Table To Reduce Run Time Of Update Query

Apr 29, 2015

I want to create index for hash table (#TEMPJOIN2) to reduce the update query run time. But I am getting "Warning!

The maximum key length is 900 bytes. The index 'R5IDX_TMP' has maximum length of 1013 bytes. For some combination of large values, the insert/update operation will fail". What is the right way to create index on temporary table.

Update query is running(without index) for 6 hours 30 minutes. My aim to reduce the run time by creating index. 

And also I am not sure, whether creating index in more columns will create issue or not.

Attached the update query and index query.

CREATE NONCLUSTERED INDEX [R5IDX_TMP] ON #TEMPJOIN2
(
[PART] ASC,
[ORG] ASC,
[SPLRNAME] ASC,
[REPITEM] ASC,
[RFQ] ASC, 

[Code] ....

View 7 Replies View Related

Transact SQL :: Return Set Of Values From SELECT As One Of Return Values From Stored Procedure

Aug 19, 2015

I have a stored procedure that selects the unique Name of an item from one table. 

SELECT DISTINCT ChainName from Chains

For each ChainName, there exists 0 or more StoreNames in the Stores. I want to return the result of this select as the second field in each row of the result set.

SELECT DISTINCT StoreName FROM Stores WHERE Stores.ChainName = ChainName

Each row of the result set returned by the stored procedure would contain:

ChainName, Array of StoreNames (or comma separated strings or whatever)

How can I code a stored procedure to do this?

View 17 Replies View Related

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

Mar 5, 2014

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

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

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

View 9 Replies View Related







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