COUNT With Mulitple Table?

Nov 3, 2006

Okay I wanted to get this to work right so I am wondering what I am doing wrong here.

"SELECT COUNT(A.Status) AS TOTAL FROM tts_tickets A,tts_reporters B WHERE A.Ref_Reporter_ID="123"AND A.Status=1"

I need to count the status options but only where from table b is the ID equal to the ID in question.

How do I do this?

View 3 Replies


ADVERTISEMENT

Mulitple Updates On Table In Same Transaction

Oct 31, 2007

 I need to update information for a user and if the user is classified
as a primary (@blnPrimary) then I need to update information for all
users within his agency (AgencyUniqueId). The issue is that the second
UPDATE to "cdds_User_Profile" always returns a rowcount of 0 (should be
1) even though the values for "@Original_AgencyUniqueId" and
"@Original_UserId" are correct. This is just a snippet of the whole
procedure. I'm trying to implement similar logic in other parts of the
procedure and I'm observing the same behavior there as well. Any help
anyone can provide is greatly appreciated. </p><pre>/*** Update User Profile ***/UPDATE [cdds_User_Profile] SET [FirstName] = @FirstName, [LastName] = @LastName, [Title] = @Title, [Phone] = @Phone, [AcctType] = @AcctType, [AcctStatus] = @AcctStatus, [LastUpdatedDate] = GETDATE() WHERE ([FirstName] = @Original_FirstName AND [LastName] = @Original_LastName AND [Title]=@Original_Title AND [Phone]=@Original_Phone AND [AcctType]=@Original_AcctType AND [AcctStatus]= @Original_AcctStatus AND [AgencyUniqueId] = @Original_AgencyUniqueIdAND [UserId] = @Original_UserId);IF @@ROWCOUNT = 0BEGINSET @err_message = 'Data has been edited by another user since you began viewing this information.'RAISERROR (@err_message,11, 1)ROLLBACK TRANSACTIONRETURNEND IF @@ERROR &lt;&gt; 0 BEGINROLLBACK TRANSACTIONRETURN ENDIF @blnPrimary = 1 BEGIN IF LOWER(@AcctStatus) &lt;&gt; LOWER(@AgencyAcctStatus)/*** Update Users Acct. Status ***//* update all users in same agency profile */UPDATE [cdds_User_Profile] SET [AcctStatus] = @AcctStatus,[LastUpdatedDate] = GETDATE() WHERE ([AgencyUniqueId] = @Original_AgencyUniqueIdAND [UserId] = @Original_UserId); IF @@ROWCOUNT = 0BEGINSET @err_message = 'Data for this agency has been edited by another user since you began viewing this information.'RAISERROR (@err_message,11, 1)ROLLBACK TRANSACTIONRETURNENDIF @@ERROR &lt;&gt; 0 BEGINROLLBACK TRANSACTIONRETURN ENDEND</pre><pre>  

View 6 Replies View Related

Table Row Count + Index Row Count

Jul 23, 2005

SQL 2000I have a table with 5,100,000 rows.The table has three indices.The PK is a clustered index and has 5,000,000 rows - no otherconstraints.The second index has a unique constraint and has 4,950,000 rows.The third index has no constraints and has 4,950,000 rows.Why the row count difference ?Thanks,Me.

View 5 Replies View Related

Mulitple Joins And Nulls

May 8, 2007

I am trying to join two tables on multiple fields.  But the nulls aren't considered a match so they aren't included in the results set. 

 Select A.Lot, A.Block, A.Plan, B.Key
from A join B on
A.Lot=B.Lot
A.Block=B.Block
A.Plan=B.Plan
 
In the data, there can be an instance where Block is null in both tables so it "matches" but not in SQL.  How do I get the "matched" nulls to be returned as well? 

View 3 Replies View Related

Update On Mulitple Records

Feb 17, 2004

I Have three tables

TASK
taskid, taskname, projectid, workid
1,,1,1
2,,1,2
3,,2,3

PROJECT
projectid, projectname
1, project1
2, project2
3, project3

WORK
workid, workname
1,work1
2,work2
3,work3

I need to do an update this way

Update the taskname as 'projectname' + '_' + 'workname' for any projectid.
projectname and workname coming from the projectid and workid in the task record

so the task table becomes
1,project1_work1,1,1
2,project1_work2,1,2
3,project2_work3,2,3

I can get all the records doing this

SELECT p.projectname+ ' ' + w.workname AS 'NEWNAME'
FROM task t
JOIN work w
ON t.workid = w.workid
JOIN project p
ON t.projectid = p.projectid
WHERE projectid = 2

how do i do an UPDATE?

any help is appreciated

View 2 Replies View Related

Seaching Mulitple Fields?

Jul 23, 2005

Hello,I need to do a seach in multiple columns for a certain word. With SQLI have to use one specific column right?I.E. select * from DB where Column1 like '%search%'That works.But what if I want to seach multiple columns in the table for thesearch word?You can't do this:select * from DB where Column1, Column2, Column3 like '%search%'Is there a way to do this?Thanks,Tmuld.

View 1 Replies View Related

JDBC With Mulitple Databases

Jul 20, 2005

Dear all,Our application needs a bit of database redundancy.Our application only accesses database for reading purposes.We want to have two databases in separate machines. Incase one databaseserver dies the application should automatically extract data from theother server.Is there any JDBC driver available so that it can detect failure in themain database server and then tries to extract data from the standbydatabase server?Kind regards--Posted via http://dbforums.com

View 2 Replies View Related

Opening Mulitple Recordsets

Jul 20, 2005

I have a single .asp page that opens a connection and then sequentiallyopens and closes 14 recordsets from stored procedures to obtain variousproduct information before closing the connection.Is it common practice to do something like this? Or is opening 14recordsets going to become a real problem when the page goes live and startsgetting high web traffic?Thank you in advance for any information you might provide.Dave

View 2 Replies View Related

Pass The Mulitple Values To A Query

Jun 12, 2001

Hi!

Can anybody help me in solving this problem

SCRIPT

declare @var1 varchar(10)
set @var1 = '1,4,9,10'
select @var1
select TGNO, TGNAME from carriers where TGNO in (@var1)

RESULT

----------
1,4,9,10

(1 row(s) affected)

Server: Msg 245, Level 16, State 1, Line 4
Syntax error converting the varchar value '1,4,9,10' to a column of data type smallint.

I want to pass a list of values to a column of DATA Type smallint.

Thanks in advance.

View 1 Replies View Related

Pass The Mulitple Values To A Query

Jun 13, 2001

What is the way to pass the values throug varibale as shown below?

SCRIPT

declare @var1 varchar(10)
set @var1 = '1,4,9,10'
select @var1
select TGNO, TGNAME from carriers where TGNO in (@var1)

RESULT

----------
1,4,9,10

(1 row(s) affected)

Server: Msg 245, Level 16, State 1, Line 4
Syntax error converting the varchar value '1,4,9,10' to a column of data type smallint.

I want to pass a list of values to a column of DATA Type smallint.

View 1 Replies View Related

Begginer In SQL-Foreign KEy To Mulitple Tables

Aug 14, 2007

Hey everyone,
I am beggining in SQL and the .NET framework and have been running into some problems trying to design a relational database. I am completely new to it so I bought a book that was recommended in this Forum called "Handbook of Relational Database Design" and it has been pretty usefull so far. RIght now I am trying to make the Logical Data Model before I make the Relational Data Model.
The problem that I am having right now is creating a table that is a derivation from another table. For example, in the book they have a table called Property, and then two other tables called MountainProperty and BeachProperty. MountainProperty and BeachProperty are a type (relationship here) of a property. So basically Property will hold some data in a table, and then MountainProperty and BeachProperty will extend that property to contain more specific data. This is very similar to what I want to do. However I am having a problem understanding how an instance (or row) in Property, will have a link (foreign key) to a piece of data that is in Mountain or BeachProperty. I understand the foreign key in Mountain and BeachProperty and how they will link back to their "parent". But how will Property know its children, where is the link for that, how can one make a link to that. You could make a column with a foreign key, but which table would it point to, can one column point to mulitple tables? That doesn't make very much sense to me.
Basically what I am trying to say is that a row in the Property table can be multiple types, and these types will store more additional data about that row. How can I link to that data from that row in the Table Property.
I am terribly sorry if this is confusing or if it is so appartently easy for you, but this is the first time that I have ever tried to make a relational database and I am really struggling on seeing how to organize these tables properly. Thank yor for your time.
Jeremy

View 3 Replies View Related

How To Generate Mulitple Reports From Parameter?

Nov 13, 2007

Hi all,

Is it possible to generate mulitple reports from parameter? what I want is for example: I have a report with a sales orders table, it has 2 input parameter fields; two dates to make up a date range. If the date range is between yesterday and today, I will get two reports (two reports with two different total page number); one is for yesterday and one is for today.

I did some research on resetting the total page, but their solution doesnt work on my special case (very complicate..). A similiar work out also apperciate.

Regards,
Bryan

View 3 Replies View Related

Inserted Rows Count From SSIS Not Like Table Rows Count

Jun 25, 2007

Hi all



i using lookup error output to insert rows into table

Rows count rows has been inserted on the table 59,123,019 mill

table rows count 6,878,110 mill ............................



any ideas

View 6 Replies View Related

Mulitple Database Connections Vs Single Connection?

Apr 16, 2008

I have a DLL that acts as an interface between the application and the database. So you create a new instance to the database via:

MyDatabaseClass db = new MyDatabaseClass()

Each instance of the class creates a new connection to the database.

So if I were to have the following, then 4 connections would be made.

MyDatabaseClass db1 = new MyDatabaseClass()
MyDatabaseClass db2 = new MyDatabaseClass()
MyDatabaseClass db3 = new MyDatabaseClass()
MyDatabaseClass db4 = new MyDatabaseClass()


My question is...What if instead of creating new connections upon each instantiation, I re-use the same connection through a "ConnectionManager" class. In this way, the above code will only create 1 connection instead of 4.

What do you guys think about each approach? Obviously the 2nd approach makes sense for non-web applications, but what about websites? Would that just cause that single connection to be overloaded??

Thanks for any insights.

View 4 Replies View Related

Retrieving An Answer From Mulitple ResultSet Statements

Jul 20, 2005

I have several ResultSet Querys/Statements within my page. An exampleof the code looks like this:ResultSet rs1 = stmt1.executeQuery("SELECT right('' + '$' + convert(varchar,SUM(ActivePrim),1), 15) AS 'ActivePrim',right(' ' + '$' + convert(varchar,SUM(KGAP),1), 15) AS'KGAP', right(' ' + '$' +convert(varchar,SUM(PrimaryRepo),1), 15) AS 'PrimaryRepo', right('' + '$' + convert(varchar,SUM(WeeklyTotal),1), 15) AS'WeeklyTotal' FROM Intranet..InsuranceStats WHERE EmployeeName ='Jamie' and Date BETWEEN '01/01/04' and '01/31/04'");What would be the correct way to retrieve each result set? Icurrently have it as the example below. But this doesn't allow foreach result set to be displayed separately.<td valign=top><b>Active Primary:</b><%= ActivePrim %></td>Any help would be greatly appreciated.Catherine

View 1 Replies View Related

Urgent Help: Regarding Assigning Mulitple Rows Of A Given Column To Variable

Aug 13, 2007

How to assign multiple values to emp1 variable separated by comma
 Ex: If  ajay karthik vijay are employee names in emp table
then emp1= ajay,karthik, vijay 
set emp1= (select employeename   from emp) returns error
error: subquery returns morethan one value
 
 
 

View 4 Replies View Related

Upgrading Mulitple 7.0 Servers To 2000 Cluster Server

Jun 6, 2002

We shall be taking a bunch of 7.0 instances and moving/upgrading to a SQL 2000 cluster server. I was thinking of creating new named instances on the 2000 cluster and upgrading each 7.0 server to it's respective named instance. Also thought of using the 2000 copy database wizard; I was told this didn't always work. Anyone hear of problems with this?
Thanks

View 2 Replies View Related

How To Split A Delimited Column Into Mulitple Rows In The Dataflow?

Jan 19, 2006

I'm sure there is probably a very easy solution that I am just not seeing or can't Google...

I have a DataFlow that includes a column of Delimited values (i.e. Value1,Value2,etc..). As this DataFlow is populating a parent table, I need split the values into their own dataflow and populate a child table. I've tried a script transformation and couldn't figure out how to accept 1 delimited input row and output multiple rows after a split. Any ideas?

TIA,
Matthew

View 1 Replies View Related

Mulitple Reports In A Single Data Driven Subscription

Oct 8, 2007

Has any figured out a work around to having multiple reports in a single email sent out by a data driven sub in SSRS 2005?

View 3 Replies View Related

Count All Table Rows Then Insert Into Test Table Using SSIS Packages

Jul 15, 2013

I have database test007DB and I need count all table rows then insert into test99 table using ssis packages .

test99: tableName countRows
t1 20
t2 30
t3 25

View 2 Replies View Related

Capturing Record Count For A Table In Oracle And Saving It In A Table In SQL Server

Jun 11, 2007

I would like to find out how to capture record count for a table in oracle using SSIS and then writing that value in a SQL Server table.



I understand that I can use a variable to accomplish this task. Well first issue I run into is that what import statement do I need to use in the design script section of Script Task. I see that in many examples following statement is used for SQL Server databases:

Imports System.Data.SqlClient



Which Import statement I need to use to for Oracle database. I am using a OLE DB Connection.



any idea?

thanks

View 16 Replies View Related

SQL Call To Count The Total Rows In Table B For Each User In Table A

Jan 17, 2006

I have 2 tables:
 
TableA:
Name
UserA
UserB
UserC
 
Table B:
Name               Data
UserA              xxx
UserB              asdasd
UserB              ewrsad
UserC              dsafasc
UserA              sdf
UserB              dfvr4
 
I want to count the total entries in Table B for every user in Table A.  The output would be:
 
Name               Count
UserA              2
UserB              3
UserC              1
 
I can use a Select Count statement, but I will have to make a SQL call for every user in Table A.  Also, Table A is dynamic, so the users are always changing.  Can this be incorporated into one SQL call to count the total rows in Table B for each user in Table A?

View 5 Replies View Related

Complex Copy Routine, Mulitple Tables And Changing GUIDs

Dec 11, 2007

hello,
I have several tables that have guids as their primary keys and the tables are related as follows:
Table1 - primary key = ServiceNo (Guid), Filter Key = CampaignNo
Table2 - primary key = CostBasisNo (Guid), Foreign Key = ServiceNo (from Table1)
Table3 - primary key = UserId, Foreign Key = ServiceNo (from table1)
Table4 - primary key = SourceServiceNo (Foreign Key from Table1), MemberServiceNo(Foreign Key from Table1)
what I need to do is copy all records from Table1 where CampaignNo = @CampaignNo and insert them into table1, this I can do easily but I will generate a new ServiceNo for each one and associated a new CampaigNo which is fine.
The problem comes in that I need to also copy the contents of Table2 = Table3 for all ServiceNos that have been copied from Table1 but insert the new Guid that will have been created when copying the rows in Table1
This is further compounded when I need to do the same to Table4 but this time I need to insert the newid's for SourceServiceNo and the related MemberServiceNo which all would have changed.
I haven't the first clue where to start with this task, do I need to use temporary tables, cursors? any help gratefully received, even if it's a pointer to the most efficient approach.
 regards
 
 
 

View 4 Replies View Related

Single Configuration File - Mulitple Packages - Elements Not Used In Each Package

Dec 18, 2007

Hi,

I'm fairly new to the SSIS world, and I've recently ported a bunch of dts packages over to SSIS. I'm an ASP.NET developer so I'm very familiar with the capabilities that configuration files give you, and I attempted to set up my solution as follows:

All of my "Data Sources" are at the project level, and added (with the same name) to each package. I wanted to have a single config file that had all of the project-level settings (i.e. connection strings, data file paths, etc). I then have a config for each package with the package level settings - i.e. variables, etc.

The problem becomes that all packages do not use all data sources. This results in an error when I try to open up a package for editing, it complains that it doesn't have a reference to data source XYZ that it is seeing in the configuration file.

Is there any way that I can get around this? If I have a password to a database change, I don't want to have to look through every config file and change it in multiple places.

View 4 Replies View Related

Service Broker Activated Procedure Getting Deadlock While Running Mulitple Queue_reader Threads

Mar 7, 2008

Hi,

I am getting deadlock on activated procedure which I am using to receive message from the Service Broker Queue.

Deadlock details:

Two threads are tring to do delete on internal table queue_messages_122847900 ends up in a dead lock.

Activated procedure code

RECEIVE TOP(1) @xmlMessage = message_body,
@handle = conversation_handle,
@message_type = message_type_name
FROM TransactionQueue;

IF (@message_type = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog')
BEGIN
END CONVERSATION @handle;
RETURN 0
END
.........................
.........................
After this I do process the message and some other processing

And then

END CONVERSATION @handle;

Note I do have single conversation group

Is their a problem in the way I am receiving and processing messages. Is it possible because of the delay between RECEIVE and END CONVERSATION same message is read by two different threads.

Thanks

View 1 Replies View Related

Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.

Aug 6, 2006

With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean        Dim bSuccess As Boolean        Dim MyConnection As SqlConnection = GetConnection()        Dim cmd As New SqlCommand("", MyConnection)        Dim i As Integer        Dim fBeginTransCalled As Boolean = False
        'messagetype 1 =internal messages        Try            '            ' Start transaction            '            MyConnection.Open()            cmd.CommandText = "BEGIN TRANSACTION"            cmd.ExecuteNonQuery()            fBeginTransCalled = True            Dim obj As Object            For i = 0 To MessageIDs.Count - 1                bSuccess = False                'delete userid-message reference                cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID"                cmd.Parameters.Add(New SqlParameter("@UserID", UserID))                cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString))                cmd.ExecuteNonQuery()                'then delete the message itself if no other user has a reference                cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1"                cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString))                obj = cmd.ExecuteScalar                If ((Not (obj) Is Nothing) _                AndAlso ((TypeOf (obj) Is Integer) _                AndAlso (CType(obj, Integer) > 0))) Then                    'more references exist so do not delete message                Else                    'this is the only reference to the message so delete it permanently                    cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2"                    cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString))                    cmd.ExecuteNonQuery()                End If            Next i
            '            ' End transaction            '            cmd.CommandText = "COMMIT TRANSACTION"            cmd.ExecuteNonQuery()            bSuccess = True            fBeginTransCalled = False        Catch ex As Exception            'LOG ERROR            GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message)        Finally            If fBeginTransCalled Then                Try                    cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection)                    cmd.ExecuteNonQuery()                Catch e As System.Exception                End Try            End If            MyConnection.Close()        End Try        Return bSuccess    End Function

View 5 Replies View Related

MDX: Count Records In Table A That Are Not In Table B

May 23, 2007

Hello all,



I would like to use MDX to identify "contracts" which are in a table A and not in a table B, and count them to have a total per "company".

It should be something like:



Contract / Flag contracts not in table B (1=yes, 0=not)

---------------------------------------------------------------

Contract 1 1

Contract 2 0

Contract 3 1

Contract 4 1

Contract 5 0

Contract 6 0

TOTAL 3



So far I know how to distinguish at contract level which records belong to table A and not table B, but I do not have the total for the company.



In SQL it should be something like that:

SELECT Company,count(*)

FROM tableA

left join tableB

on tableA.Contract = tableB.Contract

WHERE tableB.Contract is null

GROUP BY Company



Thanks,

Guillaume

View 3 Replies View Related

0 Table Row Count

Oct 11, 2000

I noticed a web query was running unreasonably slow, so I investigated
further and found out that query was searching on the primary key field
of a table, but instead of using the index seek, it acutually did a index
scan. I don't know why that query didn't use PK index, since the search
was on PK itself.

There is an other SQL server which has the exact same table(same data), I ran
that query against that table, and the query did what it suppose to do,
it used PK index, and was able to retrieve data very fast.

So I ran following commands and see if the systerm would use PK when
running the query:

(recreate all index(all non clusted))
sp_updatestat (all indexes)
sp_recompile (table)

But it didn't work, PK index was still not been used when that query was run.

Although I were able to slove the problem by force the web query to
use PK index, but I really don't like to force useage on any index.

So I thought there might be some corruptions in that table.
I didn't a dbcc showcontig, it showed that Page Density is 95%
and Frag is only 3.4% I also didn't some manual calculation
and only found very very small amount of unused space.

But when I ran sp_spaceused against that table,
and found out that the ROW COUNT for that table is 0!
but if I did select count (*), it returned the correct row count.
So I ran following commands

dbcc checkdb --- no error reported
dbcc checktable --- no error reported
dbcc updateusage (table) --- still got 0 row cound for sp_spaceused
(0 rows count in sysindexes for that table)

Question 1: Why PK index was not been used when the "where" of that query
was PK itself.

Question 2: Why that table has 0 row count?

Question 3: How can I fix the row count problem without introducing a
clustered index on that table or rebuilding that table?

Thanks guys!
Xiao

ps. that table has about 400,000 rows, and size of 20 MB

View 1 Replies View Related

Getting Count(*) From Another Table

Jul 19, 2005

select singer.id,singer.singer,count(albums.id) from singer inner join albums on albums.singer=singer.id where singer.country='England' order by singer.singer

doesnt't work because of the count(albums.id)

how can I do ?

View 3 Replies View Related

Table Count

Feb 23, 2007

hi all,
how do we sum up all the quantity in table A, and save the summary quantity into table B? can we do it live? i mean evtime quantities in table A change, the total sum in table B also change accordingly.. pliz help... thanks in advance

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

View 4 Replies View Related

Row Count From Another Table?

Mar 15, 2007

Is it possible to directly get the row count of a different table in a RS2005 report?

I'd like to use this row count number in a calculation in another table...

This would be a lot cleaner than creating a new dataset to provide me with this value.

Thanks!

View 1 Replies View Related

Getting Individual Count In Table

Mar 28, 2008

I have a link that inserts postid, catid, and postdate.  I am trying to get count of catid(how many times its in the table) then display the number on a page.  i have never tried this before.  one more thing.  Can you put a datalist inside a formview when the formview is databound already? Can someone help?  Thank you.
 

View 7 Replies View Related

How To Do 3 Count On The Same Table In One Query?

Mar 13, 2006

HelloI have this stored procedure:SELECT @openissue=ISNULL(COUNT(*),0) FROM TOpenIssue WHERE  TOpenIssue .Code <> 'CLOSED'  and  Project=@project AND DateDIFF( day, TOpenIssue .DateStart, GETDATE() ) >= 0SELECT @oiclosed=ISNULL(COUNT(*),0) FROM TOpenIssue WHERE  TOpenIssue .Code = 'CLOSED'  and  Project=@project SELECT @oipastdue=ISNULL(COUNT(*),0) FROM TOpenIssue WHERE  TOpenIssue .Code <> 'CLOSED'  and  Project=@project AND TOpenIssue .DateEnd<getdate()Is there away to optimize it in only one select statement?Thanks

View 2 Replies View Related







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