Simple Cursor To Combine Records

Sep 28, 2007



I need to return one record with concatenated string fields from a table that may contain several records. I think a cursor will be able to do what I want, but I'm not very experienced at writing them.

My data

HDR DMCD
107 TEX
107 AIR
107 LG
108 TEX
108 CAR
109 SM

I want the result of my query to find adn return each header and return the 1 or more DMCD field values concatenated. i.e.

107 TEX AIR LG
108 TEX CAR
109 SM



This is my attempt at the cursor so far


SET NOCOUNT ON

DECLARE @AACODE varchar(50),@hdr varchar(20),@dmcd varchar(20)

DECLARE AAROW_cursor CURSOR FOR

SELECT aaglhdrid,aatrxdimid

FROM aag30003



OPEN AAROW_cursor

FETCH NEXT FROM AAROW_cursor

INTo @hdr, @dmcd

WHILE @@FETCH_STATUS = 0

BEGIN

set @aacode=@aacode+@dmcd

select @hdr,@dim,@aacode



FETCH NEXT FROM aarow_cursor

INTO @hdr, @dmcd

END

CLOSE AAROW_cursor

DEALLOCATE aarow_cursor

View 5 Replies


ADVERTISEMENT

Combine And Convert Int Fields To Create One Field, Should Be Simple

Oct 19, 2007

I want to combine two of my fields somewhat like when you combine to char fields and concatenate them. But these two fields are int. How do i do that? Here's my query right now:




Code Block
SELECT AutoID,
CONVERT(Varchar(Mars_Calender_Year )+ CONVERT(Varchar(Mars_Calender_Period_Code) as MarsId
FROM NavisionReplication.dbo.Tbl_Mars_Calender
ORDER BY Mars_Calender_Year DESC








what am i doing wrong?

View 5 Replies View Related

Combine SQL Records

Nov 8, 2007

I have a SQL table with Sales Order release information.

Following are some records from the table





SMIPartNo
QtyType
PO
POLine
QtyDue
UOM
DateDue

DateDueType
fsono
fcustno

finumber
frelease
fspq

JI-117933A1
Firm
N40136001
234
200
EA
7/2/2007 0:00

SH Ship Date
E00001
20

001
1
1800

JI-117933A1
Firm
N40136001
234
400
EA
7/9/2007 0:00

SH Ship Date
E00001
20

001
2
1800

JI-117933A1
Firm
N40136001
234
400
EA
7/30/2007 0:00

SH Ship Date
E00001
20

001
3
180

If sum(QtyDue) is Less than fspq then read next record, if sum(QtyDue)>= fspq then write the record.

For the above example the output would look like the following






SMIPartNo
QtyType
PO
POLine
QtyDue
UOM
DateDue

DateDueType
fsono
fcustno

finumber
frelease
fspq

JI-117933A1
Firm
N40136001
234
1000
EA
7/2/2007 0:00

SH Ship Date
E00001
20

001
1
1800


Any help would be nice.

Thanks

David Davis

View 2 Replies View Related

Combine Two Table Records By First Name?

Feb 15, 2012

I have 2 tables First is Student_detail and another is Employee_detail. Student_detail have 14 fields like (stud_Firstname,stud_Lastname...) and Employee_detail have 17 fields like(emp_Firstname,emp_Lastname...).there is no relationship between these two table and also not in a relationship with any other table in my database.This is a structure of my db. but i want to get the records from these two table whose first name is same for both the tables.as well as the result of this query will first show me Student_detail record first and then Employee_detail record.but not in a one row.it should be display in one by one.

Like this way:

HTML Code:

Student_detail :-

stud_First_name stud_Last_name std_city ........
Shrikant Joshi Jalgaon ........
Yogesh Trivedi Malkapur ........

Employee_detail:-

emp_First_name emp_Last_name emp_city ..........
Tushar Patil Mumbai ..........
Shrikant Rane Nasik ..........

Result of a query:-
First_name Last_name City ..........
Shrikant Joshi Jalgaon .........
Shrikant Rane Nasik .........

View 14 Replies View Related

Any Ideas On How To Combine Records Into One

Mar 25, 2004

Here is what I have,

select id, name from rss_user

gives me this

r604738 one
r604738 two
r604738 three
r604739 one
r604739 two
r604739 three
r604739 four

I would like to be able to pipe this into a @temp table so it looks like this,

r604738 one,two,three
r604739 one,two,three,four


Any ideas, so far I am drawing a blank.

View 1 Replies View Related

Combine Records On Two Fields

Nov 5, 2007

Hello everyone -
This is my first post to the forum and I'm very new to SQL. I apologize if this is addressed elsewhere.

Here is an example of the results I am getting from my query

AdmissionID, sNurseInit, sSWInit
100, {NULL}, SAE
100, REG , {Null}


Is there a way to combine (merge, join? I don't know the right word) these records so that a single record for the admission is returned?

AdmissionID, sNurseInit, sSWInit
100, REG, SAE


Thanks in advance!
Amy

View 20 Replies View Related

Combine 4 Tables Without Repetitive Records

Oct 29, 2006

How to write a sql to combine the 4 tables into one without repetitive records? The 4 tables have exactly the same fields.

The tables do not have primary key. The fields to identiry the rows is name and dob. In the case the name and dob is same for two records, the one with latest date_created is selected.


Thanks

View 9 Replies View Related

How To Combine Results From Multiple Records Into One

Apr 19, 2004

Hello,

I have a table which has the following structure:

ID MessageText
001 Hello
001 There
001 Working
003 See
003 you
003 Next
003 Time

How to build a query or store procedure to return result like this:

ID MessageText
001 Hello There Working
003 See you Next Time

Your help/advice is greatly appreciated.

Thanks, Ficisa

View 14 Replies View Related

Compile/combine The Contents Of Several Records.

Dec 5, 2005

I have the following table;CREATE TABLE [x_Note] ([x_NoteId] [int] IDENTITY (1, 1) NOT NULL ,[Note] [varchar] (7200) COLLATE SQL_Latin1_General_Pref_CP1_CI_AS NOTNULL ,CONSTRAINT [PK_x_NoteId] PRIMARY KEY CLUSTERED([x_NoteId],) WITH FILLFACTOR = 90 ON [USERDATA] ,) ON [USERDATA]GOMy clients want me to take the contents of the Note column for each rowand combine them. In other words, they basically want:Note = Note [accumulated from previous rows] + Char(13) [because theywant a carriage return] + Note [from current record].What is the most efficient and relatively painless way to do this? Ithink it might require a cursor, but I'm not sure if there is a moreelegant set-based method to make this happen.

View 14 Replies View Related

How To Combine 2 Records Into 1 Unique Record

Jul 11, 2006

Hi all,We have an app that uses SQL 2000. I am trying to track when a code field(selcode) is changed on an order which then causes a status field (status)to change. I tried a trigger but the app may use 2 different updatestatements to change these fields depending on what the user does. When thetrigger fires (on update to selcode), the status field has already beenchanged. So my trigger to record the changes from inserted and deleted donot get the true 'before' value of the status field.The app does use a log table that tracks these changes. The problem I amhaving is that 2 records are created, one for the change to selcode andanother for the change to status.I am looking for help with a script to combine the existence of these 2 logrecords into 1 unique record or occurance that I can track.example:ordlog: table that logs order changesordernr: order numbervarname: name of field being changedold_value: contents of field before changenew_value: contents of field after changesyscreated: date/time of log entrySELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'selcode' and ordernr = '10580'SELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'status' and ordernr = '10580' and old_value = 'A' andnew_value = 'O'So I need a way to combine these 2 log entries into a unique occurance. Theordernr and syscreated could be used to link records. syscreated alwaysappears to be the same for the 2 log entries down to the second. Selcodecan change from NULL to a number of different values or back to NULL.Statusis either 'A' for approved or 'O' for open. An order can have many logentries during its life. The selcode may be changed several times for thesame order.Ideally, I would like a result that links 2 log entries and shows the statuschanged from 'A' to 'O' when selcode changed.Thanks for your time.

View 1 Replies View Related

Combine Multiple Records Into Single Row

Mar 29, 2007

This is how the data is organized:vID Answer12 Satisfied12 Marketing12 Yes15 Dissatisfied15 Technology15 No32 Strongly Dissatisfied32 Marketing32 YesWhat I need to do is pull a recordset which each vID is a single rowand each of the answers is a different field in the row so it lookssomething like thisvID Answer1 Answer2 Answer312 Saitsfied Marketing Yesetc...I can't quite get my mind wrapped around this one.

View 13 Replies View Related

Problem With Simple Cursor

Oct 19, 2005

I have a cursor here that appears to never stop running even though therecord set that populates it is only 22 recordsheres the code:declare cursorfinal cursor forselect appointmenteffdate, appointmentDuration, provideroid from @mainopen cursorfinalFETCH NEXT FROM cursorfinalINTO @aff, @duration, @poidWHILE @@FETCH_STATUS = 0BEGINdelete from @main_temp where (appointmenteffdate between @aff anddateadd(minute, @duration , @aff) ordateadd(minute,appointmentduration,appointmenteffd ate ) between @affand dateadd(minute, @duration , @aff))and provideroid = @poidselect @poidENDCLOSE cursorfinalDEALLOCATE cursorfinal

View 3 Replies View Related

T-SQL (SS2K8) :: Query To Combine Records In A Single Row

Jun 5, 2014

I'm working on a report where my table is as follows:

WITH SampleData (ID,NAME,[VALUE]) AS
(
SELECT 170983,'DateToday','6/04/2014'
UNION ALL SELECT 170983,'DateToday','6/04/2014'
UNION ALL SELECT 170983,'employee','1010'
UNION ALL SELECT 170983,'employee','1010'

[Code] .....

Here is my query against the table above:

SELECT
ID
,MAX(CASE WHEN NAME = 'employee' THEN VALUE END) AS PERSON
,MAX(CASE WHEN NAME = 'DateToday' THEN VALUE END) AS REQUEST_DATE
,MAX(CASE WHEN NAME = 'LeaveStartDate' THEN VALUE END) AS REQUEST_START_DATE
,MAX(CASE WHEN NAME = 'LeaveEndDate' THEN VALUE END) AS REQUEST_END_DATE
,MAX(CASE WHEN NAME = 'HoursPerDay' THEN VALUE END) AS REQUESTED_HOURS
,MAX(CASE WHEN NAME = 'LeaveType' THEN VALUE END) AS REQUEST_TYPE

FROM SampleData

Here is the result from the above query, I'm not sure how to get the desired results (listed at the end):

IDPERSONREQUEST_DATEREQUEST_START_DATE REQUEST_END_DATE REQUESTED_HOURS REQUEST_TYPE
170983NULL6/04/2014NULL NULL NULL NULL
1709831010NULL NULL NULL NULL NULL
170983NULLNULL NULL NULL 8:00 NULL
170983NULLNULL NULL 6/16/2014 NULL NULL

[Code] .....

My Desired results are as follows:

IDPERSONREQUEST_DATEREQUEST_START_DATE REQUEST_END_DATE REQUESTED_HOURS REQUEST_TYPE
17098310106/04/20146/16/2014 6/16/2014 8:00 Personal
17102416/04/20146/17/2014 6/17/2014 8:00 Bereavement

View 2 Replies View Related

Simple Cursor Script Not Working

May 21, 2008

I was wondering why this simple cursor script was not working. And by not working i mean that visual studio can't detect that there are parameters that need to be typed in. Was wondering if there was some incorrect syntax somewhere around declaring the parameter vars. Any help at all would be much appreciated.

You can checkout pastebin for colored markup by visiitng http://pastebin.com/m8f79fac

or you can checkout below:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_EmailSendMass2]

AS

DECLARE my_cursor CURSOR FOR
SELECT UserID, EmailAddress FROM vProfilesToEmail Where UserID = '132'


OPEN my_cursor


DECLARE @UserID int
DECLARE @EmailAddress varchar(255)
DECLARE @txtMessage varchar(8000)
DECLARE @txtSubject varchar(255)


FETCH NEXT FROM my_cursor
INTO @UserID, @EmailAddress

WHILE @@FETCH_STATUS = 0
-- WHILE (@@FETCH_STATUS <> -1)
BEGIN




-- Send Email
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'ZenzuuNoreply',
@recipients = @EmailAddress,
@body = @txtMessage,
@subject = @txtSubject;

-- Insert Sent Email
INSERT INTO [EmailArchives] ([EmailAddress], [Sent]) VALUES (@EmailAddress, 'True')


FETCH NEXT FROM my_cursor
INTO @UserID, @EmailAddress
END

CLOSE my_cursor
DEALLOCATE my_cursor

GO

View 1 Replies View Related

T-SQL (SS2K8) :: Simple Cursor Runs Infinite Loop?

Dec 23, 2014

I'm trying to build a simple cursor to understand how they work. From the temp table, I would like to print out the values of the table, when I run my cursor it just keeps running the output of the first row infinitely. I just want it to print out the 7 rows in the table ...

IF OBJECT_ID('TempDB..#tTable','U') IS NOT NULL
DROP TABLE #tTable
CREATE TABLE #tTable

[Code]....

View 2 Replies View Related

SQL Server 2014 :: Combine Records That Are Identical And SUM Values In Price Field

Sep 30, 2015

I have a robust query that returns a dataset and the data is good, however some of the records contain the exact same data with the exception of the 'Price' field. I want to combine the records that are identical and SUM the values in the 'Price' field. My query and example return dataset is below.

Query:
--------
select distinct
'On-Demand' as 'Business Line',
o.OrderID as 'Order #',
isnull(d.DisplayCode,'UNK') as Hub,
isnull(rz.RouteID,'UNK') as 'Default Route',
'On-Demand' as 'Assigned Route',

[Code] ....

View 4 Replies View Related

How To Use CURSOR For Updating Records

Mar 8, 2000

Hello Everyone,

I have a table with 5 columns (col1, col2, col3, col4). I want to do is:
1) To check if any two records are duplicates (if the the values in col1 of record A are identical to Record B, two records are considered as duplicates);

2) if two records are duplicate, I want to mark Record B as "Dup" in col4 ;

3) move the data of Col2 of Record B to col3 of Record A.

I have tried to use CURSOR for the job. I would appreciate if anyone can give me some hints for updating records using Cursor.

My script looks like this:
CREATE PROC Mark_duplicate
AS
DECLARE @var1_a, /* To hold the data from Record A */
@var2_a,
@var3_a,
@var4_a,
@var5_a,

@var1_b, /* To hold the data from Record B */
@var2_b,
@var3_b,
@var4_b,
@var4_b,

/*** Create a CURSOR ***/
DECLARE Dup CURSOR
FOR SELECT col1, col2, col3, col4
FROM TableA ORDER BY col1, col2
FOR UPDATE OF col1, col2, col3, col4

/**** OPEN the CURSOR ****/
OPEN Dup
FETCH NEXT FROM Dup into @var1_a, @var2_a, @var3_a, @var4_a
WHILE ( @@FETCH_STATUS =0 )
BEGIN
FETCH NEXT FROM Dup into @var1_b, @var2_b, @var3_b, @var4_b
WHILE ( @@FETCH_STATUS =0 )
BEGIN
If ( @var1_a = var1_b ) THEN
.
.Updating statements
.
.
ELSE
SET @VAR1_a = @var1_b, @VAR2_a = @var2_b,
@VAR3_a = @var3_b, @VAR4_a = @var4_b
FETCH NEXT FROM Dup into @var1_b, @var2_b, @var3_b, var4_b
END
END
CLOSE DUP
.
.
.

Thanks a lot. Have a good day!

Lunjun

View 2 Replies View Related

Selecting Records Using Cursor ???

Apr 2, 2008

hi ,
how can i have a stored procedure that selects records using cursor
and returns the cursor ?


thanx in advance

View 6 Replies View Related

Breakout Records Based On UNIT Total Without Cursor

Jan 30, 2008

I have a set of revenue records where there is a UNIT column and a REVCHARGE column. What I need to do is breakout the records into single records where the unit count is > 1 and calc the actual charge:

Ex:

Units REVCHG FIELD_A FIELD_B .....
3 3.00 ABCD EFGH

Needs to be converted to:

Units REVCHG FIELD_A FIELD_B .....
1 1.00 ABCD EFGH
1 1.00 ABCD EFGH
1 1.00 ABCD EFGH

The calc is obvious but how can I do this with a cursor but would like to do it without a cursor if possible? Anybody got an idea?

Thanks.

View 6 Replies View Related

Help! A Simple &#39;update Records&#39; Question

Nov 19, 1999

Hi there,

I was trying to update records of a recordset(ADODB.Recordset) returned from a stored procedure(SQL server 7.0) in ASP file, this stored procedure select records into a temporary table, so the records returned by the SP actually physically are in tempdb database rather than in the user database.

When executing Update statement , I got the error message:
Microsoft OLE DB Provider for ODBC Drivers error '80040e37'
[Microsoft][ODBC SQL Server Driver][SQL Server]Database name 'Mydatabase' ignored, referencing object in tempdb.

Any ideas/comments would be highly appreciated!
Dana Jian
dan_jian@hotmail.com

View 1 Replies View Related

Looking For Simple Purge Of Records From A Table

May 21, 2007

greets all, ive got a table with batches of records. each group of records has a batch id as part of the PK in the form BTCXXXX where XXXX is an auto-incremented number. so lets say i have 100 batches of 20k records per batch in the table. so the distinct batch ids are BTC0200 (oldest batch) through BTC0300 (newest batch).
i only want to keep the 90 most recent batches in the table at any given time.
is it ok to just subtract 90 from the last batch id and do something like:

DECLARE @batch_id char(10)
SET @batch_id = 'BTC' + batch_num-90

DELETE FROM ITEM_BATCH
WHERE BATCH_ID < @batch_id

i want to cover if the table has more than 90 batches and if the table has less then 90 batches. is this a feasible approach?

View 4 Replies View Related

Problem Of Duplicate Records With A Simple Insert Statement !

Oct 11, 2007

 
I am using a simple stored proc shown below which inserts a record and updates the same record field called SortID with the Primary Key Column data of the same record.Everything was working fine until few days back. The site has been deployed 2 years back and was LIVE ever since.
We have got thousands of records in this Credits table. The table field called SortID is used for moving the credits up and down.
My problem is now after 2 years of deploying the table has got duplicate records, suprisingly a same credit is appearing under different MemberID and with the same SortID.
How are these duplicate records inserted with a simple insert statement & update ??
Is this a Locking problem or Transaction problem I have no idea.
Any ideas will be of great help
Thanks in Advance
Stored Procedure Used

CREATE PROC SP_SC_INSERT (@memberID int,@title varchar(30),@dir varchar(30),@desc varchar(20))ASINSERT INTO [dbo].[Credits]([MemberID],[Title],[Director], [Description], )VALUES(@memberID,@title,@dir, @desc, )UPDATE Credits Set SortID = @@IDENTITY WHERE CreditID = @@IDENTITYGO 

View 4 Replies View Related

Simple Count Function - Show All Records For SSN In A Table

Jul 9, 2013

I want my query to list all SSNS that have more than one record in the table. I have this query:

Code:

SELECT SSN, name4, count(*) from [1099_PER]
group by SSN, name4
having count(SSN) > 1

It does retrieve the right SSNS and tells me how many times the SSN occurs in the table. However, I want my query results to display their full records.

For example

SSN NAME4 COUNT
123445555 WALTER - 4

I want the query to show me all four records for this SSN. I thought removing the count field would do this, but it still gives me only one instance of each SSN.

View 6 Replies View Related

WARNING. A Simple Cut And Paste Of 8 Records Can Distroy A SQL Server Table

Jul 20, 2005

Today I need to copy 8 records in a table. I have to use Access 200 becauseof the limitation of Enterprise Manager's inability to cope with field withmore than 900 characters. Selected records, cut, paste. I got an erroormessage about not being able to have a null Key_ID (I copied the reords andtried to paste the Key_ID as part of the records - normally I hide theKey_ID).Now I can't access either the new records or the originals that I was tryingto copy (because, it would seem, they have identical primary keys). I alsocannot export the table via DTS 'unspecified error' and 'integrityviolation'.Or delete the offending records with a Query Anaylyser delete query.Basically the entire SQL Server database has been destroyed with a couple ofkeystrokes.Now, I've being developing database applications for over 20years and theone thing, maybe the only thing I expect from a database server is toprotect the integrity of my data. SQL Server does not, it would seem. Theserecords aren't just any random unimportant records either. They contain the'create views' that my entire application require to function and each oneapproaches the 8000 record limit and have take years to perfect and justchecking that the table is valid could take me days.

View 5 Replies View Related

DB Engine :: Can Deleted Records Be Recovered In Simple Recovery Model?

Aug 21, 2015

Can the deleted records be recovered in Simple Recovery model database? Are the delete logs present there?

View 3 Replies View Related

Insert / Update In Master Table And Also Save A History Of Changed Records : Using Data Flow/simple Sql Queries

Feb 9, 2007

Hi,

My scenario:

I have a master securities table which has 7 fields. As a part of the daily process I am uploading flat files into database tables. The flat files contains the master(static) security data as well as the analytics(transaction) data. I need to

1) separate the master (static) data from the flat files,

2) check whether that data is present in the master table, if not then insert that data into the master table

3) If data present then move that existing record to an history table and then update the main master table.

All the 7 fields need to be checked to uniquely identify a single record in the master table.

How can this be done? Whether we can us a combination of data flow items or write a sql procedure to do all this.

Thanks in advance for your help.

Regards,

$wapnil

View 4 Replies View Related

Transact SQL :: STATIC Defines A Cursor That Makes Temporary Copy Of Data To Be Used By Cursor

Aug 12, 2015

In MSDN file I read about static cursor

STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in
tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications

It say's that modifications is not allowed in the static cursor. I have a  questions regarding that

Static Cursor
declare ll cursor global static
            for select  name, salary from ag
  open ll
             fetch from ll
 
              while @@FETCH_STATUS=0
               fetch from ll
                update ag set salary=200 where 1=1
 
   close ll
deallocate ll

In "AG" table, "SALARY" was 100 for all the entries. When I run the Cursor, it showed the salary value as "100" correctly.After the cursor was closed, I run the query select * from AG.But the result had updated to salary 200 as given in the cursor. file says  modifications is not allowed in the static cursor.But I am able to update the data using static cursor.

View 3 Replies View Related

Dynamic Cursor Versus Forward Only Cursor Gives Poor Performance

Jul 20, 2005

Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin

View 1 Replies View Related

Could Not Complete Cursor Operation Because The Set Options Have Changed Since The Cursor Was Declared.

Sep 20, 2007

I'm trying to implement a sp_MSforeachsp howvever when I call sp_MSforeach_worker
I get the following error can you please explain this problem to me so I can over come the issue.


Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 31

Could not complete cursor operation because the set options have changed since the cursor was declared.

Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 32

Could not complete cursor operation because the set options have changed since the cursor was declared.

Msg 16917, Level 16, State 1, Procedure sp_MSforeach_worker, Line 153

Cursor is not open.

here is the stored procedure:


Alter PROCEDURE [dbo].[sp_MSforeachsp]

@command1 nvarchar(2000)

, @replacechar nchar(1) = N'?'

, @command2 nvarchar(2000) = null

, @command3 nvarchar(2000) = null

, @whereand nvarchar(2000) = null

, @precommand nvarchar(2000) = null

, @postcommand nvarchar(2000) = null

AS

/* This procedure belongs in the "master" database so it is acessible to all databases */

/* This proc returns one or more rows for each stored procedure */

/* @precommand and @postcommand may be used to force a single result set via a temp table. */

declare @retval int

if (@precommand is not null) EXECUTE(@precommand)

/* Create the select */

EXECUTE(N'declare hCForEachTable cursor global for

SELECT QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME)

FROM INFORMATION_SCHEMA.ROUTINES

WHERE ROUTINE_TYPE = ''PROCEDURE''

AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME)), ''IsMSShipped'') = 0 '

+ @whereand)

select @retval = @@error

if (@retval = 0)

EXECUTE @retval = [dbo].sp_MSforeach_worker @command1, @replacechar, @command2, @command3, 0

if (@retval = 0 and @postcommand is not null)

EXECUTE(@postcommand)

RETURN @retval



GO


example useage:


EXEC sp_MSforeachsp @command1="PRINT '?' GRANT EXECUTE ON ? TO [superuser]"

GO

View 7 Replies View Related

Join Cursor With Table Outside Of Cursor

Sep 25, 2007

part 1

Declare @SQLCMD varchar(5000)
DECLARE @DBNAME VARCHAR (5000)

DECLARE DBCur CURSOR FOR
SELECT U_OB_DB FROM [@OB_TB04_COMPDATA]

OPEN DBCur
FETCH NEXT FROM DBCur INTO @DBNAME


WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @SQLCMD = 'SELECT T0.CARDCODE, T0.U_OB_TID AS TRANSID, T0.DOCNUM AS INV_NO, ' +
+ 'T0.DOCDATE AS INV_DATE, T0.DOCTOTAL AS INV_AMT, T0.U_OB_DONO AS DONO ' +
+ 'FROM ' + @DBNAME + '.dbo.OINV T0 WHERE T0.U_OB_TID IS NOT NULL'
EXEC(@SQLCMD)
PRINT @SQLCMD
FETCH NEXT FROM DBCur INTO @DBNAME

END

CLOSE DBCur
DEALLOCATE DBCur


Part 2

SELECT
T4.U_OB_PCOMP AS PARENTCOMP, T0.CARDCODE, T0.CARDNAME, ISNULL(T0.U_OB_TID,'') AS TRANSID, T0.DOCNUM AS SONO, T0.DOCDATE AS SODATE,
SUM(T1.QUANTITY) AS SOQTY, T0.DOCTOTAL - T0.TOTALEXPNS AS SO_AMT, T3.DOCNUM AS DONO, T3.DOCDATE AS DO_DATE,
SUM(T2.QUANTITY) AS DOQTY, T3.DOCTOTAL - T3.TOTALEXPNS AS DO_AMT
INTO #MAIN
FROM
ORDR T0
JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN DLN1 T2 ON T1.DOCENTRY = T2.BASEENTRY AND T1.LINENUM = T2.BASELINE AND T2.BASETYPE = T0.OBJTYPE
LEFT JOIN ODLN T3 ON T2.DOCENTRY = T3.DOCENTRY
LEFT JOIN OCRD T4 ON T0.CARDCODE = T4.CARDCODE
WHERE ISNULL(T0.U_OB_TID,0) <> 0
GROUP BY T4.U_OB_PCOMP, T0.CARDCODE,T0.CARDNAME, T0.U_OB_TID, T0.DOCNUM, T0.DOCDATE, T3.DOCNUM, T3.DOCDATE, T0.DOCTOTAL, T3.DOCTOTAL, T3.TOTALEXPNS, T0.TOTALEXPNS


my question is,
how to join the part 1 n part 2?
is there posibility?

View 1 Replies View Related

Simple Simple Linking Tables & Perform Calculation

Mar 22, 2007

found it

View 3 Replies View Related

SQL 2012 :: Query To Make Single Records From Multiple Records Based On Different Fields Of Different Records?

Mar 20, 2014

writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.

ID effdate termdate
556868 1999-01-01 1999-06-30
556868 1999-07-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-01-31
556872 2004-02-01 2004-02-29

output should be ......

ID effdate termdate
556868 1999-01-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-02-29

View 0 Replies View Related

Simple Question (Hope Simple Answer Too)

May 26, 2004

Hey,

I have MS SQL database.
I have procedure:



code:--------------------------------------------------------------------------------
CREATE PROCEDURE dbo.Reg_DropTable
@ModuleId varchar(10)
AS
declare @TableName varchar, @kiek numeric
set @TableName = 'reg_'+@ModuleId

begin
DROP TABLE @TableName <- HERE I GOT ERROR
end
GO
--------------------------------------------------------------------------------


I got error when using variable with tables names.
How to do this?

Ps. Number is send to this function and it must drop table with name Reg_[That number]

View 1 Replies View Related







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