Monster Select Statement Revisited

Mar 11, 2007

I have a database with a date of birth.  From this, I need to select records that include a large number of variables including records where an individual is older than a selected age and/or younger than a selected age, and even worse, of a given astrological sign if one is selected. 
I'm currently using a strongly typed dataset.  Is this something that's do-able with a dataset, or should I build the select string on the form programmatically?   I have an ASP site that I'm re-writing in ASP.NET 2.0.  In the ASP site the select string includes the code below.  I just don't see how  I can do this in a dataset.
if (strLowerAge <> 18) or (strUpperAge <> 99) then
      If (strLowerAge <> "") Then
         strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DateDiff(yyyy, [DATE OF BIRTH], '" & date & "') >= " & strLowerAge & ")"
      End If
      If (strUpperAge <> "") Then
         If (strSQL <> "") Then
            strSQL = strSQL & " AND (DateDiff(yyyy, [DATE OF BIRTH], '" & date & "') <= " & strUpperAge & ")"
         Else
            strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DateDiff(yyyy, [DATE OF BIRTH], '" & date & "') <= " & strUpperAge & ")"
         End If
      end if
   End If
   If (strAstSign <> "") Then
      Select Case strAstSign
         Case "Aries 3/21 - 4/19"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 3 AND DATEPART(d,[DATE OF BIRTH]) > 20 ) OR (DATEPART(m,[DATE OF BIRTH]) = 4 AND DATEPART(d,[DATE OF BIRTH]) < 20 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m, [DATE OF BIRTH]) = 3 AND DATEPART(d, [DATE OF BIRTH]) > 20 ) OR (DATEPART(m, [DATE OF BIRTH]) = 4 AND DATEPART(d, [DATE OF BIRTH]) < 20 )"
            End If
         Case "Taurus 4/20 - 5/20"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 4 AND DATEPART(d,[DATE OF BIRTH]) > 19 ) OR (DATEPART(m,[DATE OF BIRTH]) = 5 AND DATEPART(d,[DATE OF BIRTH]) < 21 ))"
           Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 4 AND DATEPART(d,[DATE OF BIRTH]) > 19 ) OR (DATEPART(m,[DATE OF BIRTH]) = 5 AND DATEPART(d,[DATE OF BIRTH]) < 21 )"
            End If
         Case "Gemini 5/21 - 6/20"
            If (strSQL <> "") Then
              strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 5 AND DATEPART(d,[DATE OF BIRTH]) > 20 ) OR (DATEPART(m,[DATE OF BIRTH]) = 6 AND DATEPART(d,[DATE OF BIRTH]) < 21 ))"
           Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 5 AND DATEPART(d,[DATE OF BIRTH]) > 20 ) OR (DATEPART(m,[DATE OF BIRTH]) = 6 AND DATEPART(d,[DATE OF BIRTH]) < 21 )"
            End If
         Case "Cancer 6/21 - 7/22"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 6 AND DATEPART(d,[DATE OF BIRTH]) > 20 ) OR (DATEPART(m,[DATE OF BIRTH]) = 7 AND DATEPART(d,[DATE OF BIRTH]) < 23 ))"
           Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 6 AND DATEPART(d,[DATE OF BIRTH]) > 20 ) OR (DATEPART(m,[DATE OF BIRTH]) = 7 AND DATEPART(d,[DATE OF BIRTH]) < 23 )"
            End If  
         Case "Leo 7/23 - 8/22"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 7 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 8 AND DATEPART(d,[DATE OF BIRTH]) < 23 ))"
           Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 7 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 8 AND DATEPART(d,[DATE OF BIRTH]) < 23 )"
            End If
         Case "Virgo 8/23 - 9/22"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 8 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 9 AND DATEPART(d,[DATE OF BIRTH]) < 23 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 8 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 9 AND DATEPART(d,[DATE OF BIRTH]) < 23 )"
            End If
         Case "Libra 9/23 - 10/22"
            If (strSQL <> "") Then
              strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 9 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 10 AND DATEPART(d,[DATE OF BIRTH]) < 23 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 9 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 10 AND DATEPART(d,[DATE OF BIRTH]) < 23 )"
            End If
         Case "Scorpio 10/23 - 11/21"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 10 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 11 AND DATEPART(d,[DATE OF BIRTH]) < 22 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 10 AND DATEPART(d,[DATE OF BIRTH]) > 22 ) OR (DATEPART(m,[DATE OF BIRTH]) = 11 AND DATEPART(d,[DATE OF BIRTH]) < 22 )"
            End If
         Case "Sagittarius 11/22 - 12/21"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 11 AND DATEPART(d,[DATE OF BIRTH]) > 21 ) OR (DATEPART(m,[DATE OF BIRTH]) = 12 AND DATEPART(d,[DATE OF BIRTH]) < 22 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 11 AND DATEPART(d,[DATE OF BIRTH]) > 21 ) OR (DATEPART(m,[DATE OF BIRTH]) = 12 AND DATEPART(d,[DATE OF BIRTH]) < 22 )"
            End If
         Case "Capricorn 12/22 - 1/19"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 12 AND DATEPART(d,[DATE OF BIRTH]) > 21 ) OR (DATEPART(m,[DATE OF BIRTH]) = 1 AND DATEPART(d,[DATE OF BIRTH]) < 20 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 12 AND DATEPART(d,[DATE OF BIRTH]) > 21 ) OR (DATEPART(m,[DATE OF BIRTH]) = 1 AND DATEPART(d,[DATE OF BIRTH]) < 20 )"
            End If
         Case "Aquarius 1/20 - 2/18"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 1 AND DATEPART(d,[DATE OF BIRTH]) > 19 ) OR (DATEPART(m,[DATE OF BIRTH]) = 2 AND DATEPART(d,[DATE OF BIRTH]) < 19 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 1 AND DATEPART(d,[DATE OF BIRTH]) > 19 ) OR (DATEPART(m,[DATE OF BIRTH]) = 2 AND DATEPART(d,[DATE OF BIRTH]) < 19 )"
            End If
         Case "Pisces 2/19 - 3/20"
            If (strSQL <> "") Then
               strSQL = strSQL & " AND ((DATEPART(m,[DATE OF BIRTH]) = 2 AND DATEPART(d,[DATE OF BIRTH]) > 18 ) OR (DATEPART(m,[DATE OF BIRTH]) = 3 AND DATEPART(d,[DATE OF BIRTH]) < 21 ))"
            Else
               strSQL = "SELECT [DATE OF BIRTH], [FIRST NAME], [LAST NAME], [STATE], [MALE OR FEMALE] FROM members WHERE (DATEPART(m,[DATE OF BIRTH]) = 2 AND DATEPART(d,[DATE OF BIRTH]) > 18 ) OR (DATEPART(m,[DATE OF BIRTH]) = 3 AND DATEPART(d,[DATE OF BIRTH]) < 21 )"
            End If
      End Select  
   END IF

Diane 

View 3 Replies


ADVERTISEMENT

Monster Query Assistance

Mar 5, 2007

I realize this query is inherently incorrect, but my issue is mainly
syntax. The line, "WHEN a.order_id <> b.order_id THEN" is wrong.
I want to ensure that a.order_id is not in the settlement table. So I
was thinking something along the lines of "WHEN a.order_id not in
(select order_id from settlement)" which I know will cause a slower
response time, but I'm willing to deal with it. In any case, that
syntax doesn't appear to work.

sum(
CASE
WHEN a.ready_to_pay_flag = 'Y' and a.deduction_type = 'E' and (
CASE
WHEN a.order_id <> b.order_id THEN
a.transaction_date
ELSE
b.delivery_date
END) used_date datediff(d,used_date, ".$cutOffDate.") < 30) THEN
a.amount
END) earn_amount_rtp_curr,

Any help here would be hotness!

Thanks!

View 9 Replies View Related

Select Statement Within Select Statement Makes My Query Slow....

Sep 3, 2007

Hello... im having a problem with my query optimization....

I have a query that looks like this:


SELECT * FROM table1
WHERE location_id IN (SELECT location_id from location_table WHERE account_id = 998)


it produces my desired data but it takes 3 minutes to run the query... is there any way to make this faster?... thank you so much...

View 3 Replies View Related

RDLC Vs RDL Revisited

May 8, 2007

I have searched the archive of this forum, and based on some previous answers have read the followin FAQ



http://www.gotreportviewer.com/



However, even so, I still have a questoin about when to use RDLC vs RDL from the point of view of licensing and load sharing betwee DB and report server.



1. As we all know that SSRS will take a license of SQL Server if the web service is deployed on any other machine other than SQL Server (which is normally the case because no serious DBA will allow IIS apps to be installed on the DB Server). Also, if the SSRS is deployed on NLB cluster then each node of the cluster would need a "SQL Enterprise" license. (which can be very expensive).

2. Co deploying the SSRS with SQL Server is a bad idea because it puts excessive load on the DB+Report Server.

3. Since there is no "load balancing" in SQL all the rendering has to be done by the SSRS service which is running on the DB Server.



Now compare this to RDLC



1. RDLC gives me the same engine as RDL

2. However it has no licensing tags to it.

3. I can deploy ASP.NET report viewer on my web farm and scale it out as much as I like.

4. Extract data from the DB using stored procedures.



So it seems that RDLC solution is cheaper, gives better scale out capabilities and also moves the rendering of reports on the web farm rather than the Report Server.



Why should me or anyone else choose RDL at all?



There seems to be one disadvantage that the data has to fetched programmatically and manually binded (like an ASP.NET app) as RDLC does not provide any feature to connect to data sources. But this is not much when you see the cost and scalability benefits.



regards,

Abhishek.

View 6 Replies View Related

SQL Server Question Revisited-What Is The Best Way??

Mar 16, 2004

I am new to this but here goes.
I have a sqlserver with asp.net.I have a stored procedure in the database
named Try_Login .I need to know how and what is the best way to accomplish my task.I need the data in the stored procedure after it runs.Do I use the ExecuteReader() Method or how do I go about retrieving these values?????

CREATE procedure dbo.Try_Login
(
@LoginName nvarchar(15),
@Password NvarChar(15)
)
as
select
UserName,
UserPassword,
UserClinic,
UserTester
from
Clinic_users
where
UserName = @LoginName
and
UserPassword = @Password

What I need to know is how to get my code to correspond with it.I.E. I have a login in form...
txtUsername and txtPassword need to be passed to this Stored procedure.
I assume you use .value to obtain thier values.Here is my code so far......

Public Sub LoginDB()
Dim conLogin As SqlConnection
Dim cmdLogin As SqlCommand
Dim dtrLogin As SqlDataReader
conLogin = New SqlConnection ("Server=myserver;database=APPOINTMENTS;uid=XXXX;pwd=XXXX")
cmdLogin = New SqlCommand("Try_Login ", conLogin)
cmdLogin.CommandType = CommandType.StoredProcedure
cmdLogin.Parameters.Add("@LoginName",txtUsername.Text)
cmdLogin.Parameters.Add("@Password",txtPassword.Text)

dtrLogin = cmdLogin.ExecuteReader()

While dtrLogin.Read()

End While
End Sub

I have no clue why it does not work..........

View 1 Replies View Related

Basic Query Help - Revisited

Jul 14, 2001

I'm not getting it. The query below "e.g." is exactly as I think it should be except for the <Join Clause> as there is only the match on site name. I tried joing on the site name, but only got the sites in the log. I want all the site names even if they don't have a log item for a given date range.

I'd post my real query if it would help, it's just that I'm chopping up some strings and converting some time stamps to dates as varchar for readability for the final report, which is an MSExcel pivot table.

My original post lies below.

TIA

jEfFp...

Reply...
Date: Basic Query Help (reply)
RickD (Rick.Davis@Schroders.com)
7/11/01 6:41:26 AM

Make log an outer join to site.

e.g

select s.name, l.ondate from
site s
RIGHT OUTER JOIN log l ON <Join Clause> where
substring(id,3,6) in(select name from site)
and ondate between getdate()-8 and getdate()-1

You didn't seem to have any logical join between the tables, but i'm sure you have, just put this in the <Join Clause>.

Oh, and read BoL, it helps no end.....

------------
Original Post...
Jeff Proctor at 7/10/01 11:18:31 PM

my 7 day query....

select s.name, l.ondate from
site s, log l where
substring(id,3,6) in(select name from site)
and ondate between getdate()-8 and getdate()-1

This returns those sites that exist in the current log, however what I want is a result set that has a row for each name regardless if they are in the log.

I have 2 tables...

table1 sites
name
smithj
anandt
burtot
proctj
etc....

table2 log
id ondate
02anandt 07/01/01
02anandt 07/03/01
02anandt 07/03/01
01smithj 07/03/01
03burtot 07/05/01
01smithj 07/05/01
03burtot 07/05/01
etc.....

View 1 Replies View Related

Error 18452 Revisited

Feb 16, 2000

I keep getting this error when tring to log in to a SQL 7 db from a client application written in VB6.

The text reads:

Login failed for user 'rmuser'. Reason: Not associated with a trusted SQL Server connection.

I have the account setup in SQL security and I have the account listed in the database and I'm using named pipes on a common domain. I'm running out of options. The network is a mix of Novell and NT. Please help

View 1 Replies View Related

Convert Question Revisited

Nov 20, 2000

hi,

I guess my brain isn't functioning on monday morning. I am trying to do a convert with little success.

what I want to do is insert a character string into a smallint column of a table. i.e.

DECLARE @a char(6)
select @a = 'string'




I have tried the following and variations on it, but get a syntax error

insert table testtable (1,convert(smallint,@a))

The columns in testtable are both smallint datatypes.


Thanks in advance



-- I got this response, but seem to get a convert error even
when using the below example


Try this :

DECLARE @a char(6),
@b smallint
select @a = 'string'
select @b = convert(smallint, @a)

insert testtable values (1, @b)


any suggestions?

View 2 Replies View Related

Passing A Parameter Into SQL OpenQuery, Revisited

Nov 10, 2003

Greetings. ASP.NET neophyte seeking a bit of advice. I am looking for the specific syntax that allows me to pass a local variable into an open query within SQL 2000 for a linked server, such as:

SELECT [ticketno] from OpenQuery(JWS_GR, 'select ticketno from tksmisc where itemno = 1 AND ticketno = @scaleticketno')

I included the variable @scaleticketno here where I was using an actual value. This doesn't work, returning the eqivalent of a database 'DUH?' message because the linked server database engine (Pervasive SQL 2000i) has no idea how to treat @scaleticketno. (Nor do I.) Any thoughts, suggestions or recommendations would be much appreciated and regarded with eternal gratitude.

View 1 Replies View Related

SSRS Audit Report Revisited

Oct 2, 2007

Building on the thread http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2205669&SiteID=1 which Jessica Moss posted the code below:




Code Block
select u.UserName, c.Path, r.RoleName
from ReportServer.dbo.PolicyUserRole pur
left join ReportServer.dbo.Users u on pur.userID=u.userID
left join ReportServer.dbo.Roles r on pur.roleID=r.roleID
left join ReportServer.dbo.Catalog c on pur.policyID=c.policyID
order by u.UserName, c.Path, r.RoleName





I tried to take it one step further and add a parameter where I could just type in the users Active Directory login id, thus limiting the result set. I also wanted to avoid having to type in the domainnameuserid for each parameter and only wanted to type the userid. So I changed the code (see below) and added a multi-value parameter called users.




Code Block
select u.UserName, c.Path, r.RoleName
from ReportServer$SQL2005DSS.dbo.PolicyUserRole pur
left join ReportServer$SQL2005DSS.dbo.Users u on pur.userID=u.userID
left join ReportServer$SQL2005DSS.dbo.Roles r on pur.roleID=r.roleID
left join ReportServer$SQL2005DSS.dbo.Catalog c on pur.policyID=c.policyID
where u.Username IN('DOMAINNAME' + @Users)
order by u.UserName, c.Path, r.RoleName




Unfortunately, if I type:
Domainnamejblack
Domainnamejdoe
Domainnameefranks

I only get a return for the first userid entered. Any ideas?

View 4 Replies View Related

Multiple Tables Used In Select Statement Makes My Update Statement Not Work?

Aug 29, 2006

I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly.  My problem is that the table I am pulling data from is mainly foreign keys.  So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys.  I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit.  I run the "test query" and everything I need shows up as I want it.  I then go back to the gridview and change the fields which are foreign keys to templates.  When I edit the templates I bind the field that contains the string value of the given foreign key to the template.  This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value.  So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors.  I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode.  I make my changes and then select "update."  When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing.  The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work.  When I remove all of my JOIN's and go back to foreign keys and one table the update works again.  Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People].  My WHERE is based on a control that I use to select a person from a drop down list.  If I run the test query for the update while setting up my data source the query will update the record in the database.  It is when I try to make the update from the gridview that the data is not changed.  If anything is not clear please let me know and I will clarify as much as I can.  This is my first project using ASP and working with databases so I am completely learning as I go.  I took some database courses in college but I have never interacted with them with a web based front end.  Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian 

View 5 Replies View Related

Returning Range Of Records From SQL Server 7 - Old Issue Revisited

Oct 19, 2006

Hi all,I am using the following stored procedure in SQL 7 to return a range of records.CREATE PROCEDURE spRetMyTable@maxRows int, @lastRecord int, @SortPhrase varchar(122)ASbeginDECLARE @stSql VARCHAR(255) SET ROWCOUNT @maxRowsSET @stSql = 'SELECT * FROM (SELECT TOP 10 colPrimary, col1, col2, col3 FROM (SELECT TOP ' + CONVERT(VARCHAR, @lastRecord) +     'colPrimary, col1, col2, col3 FROM [MyTable] ORDER BY [colPrimary] ASC) AS tbl1 ORDER BY [colPrimary] DESC) AS tbl2 ORDER by [colPrimary] ASC'exec(@stSql)set rowcount 0endTo execute the above procedure I am issuing the command:execute spRetMyTable @maxRows 10, @lastRecord 1500The column [colPrimary] is the primary field in the table.I will be using the selected records in a gridView with paging (3 records per page). So if the next page is selected I would require to take out record 1491 to record 1494 and Add record 1501 to record 1503 in the datatable subject to the availability of records in the table MyTable.How do I provide sorting by col1, col2 or col3? It could be single column or multiple column sorting as chosen by the user during runtime.Is there any performance overhead in the above method in the first place?Could it be improved by any alternative process?I need YOUR ASSISTANCE to cater to the above issues in a feasible way.Thanks in advance. 

View 2 Replies View Related

SQL Server 2012 :: Create Dynamic Update Statement Based On Return Values In Select Statement

Jan 9, 2015

Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".

Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.

View 4 Replies View Related

Using Conditional Statement In Stored Prcodure To Build Select Statement

Jul 20, 2005

hiI need to write a stored procedure that takes input parameters,andaccording to these parameters the retrieved fields in a selectstatement are chosen.what i need to know is how to make the fields of the select statementconditional,taking in consideration that it is more than one fieldaddedfor exampleSQLStmt="select"if param1 thenSQLStmt=SQLStmt+ field1end ifif param2 thenSQLStmt=SQLStmt+ field2end if

View 2 Replies View Related

TSQL - Use ORDER BY Statement Without Insertin The Field Name Into The SELECT Statement

Oct 29, 2007

Hi guys,
I have the query below (running okay):



Code Block
SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02'
FROM myTables
WHERE Conditions are true
ORDER BY Field01

The results are just as I need:


Field01 Field02

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

192473 8461760

192474 22810



Because other reasons. I need to modify that query to:



Code Block
SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02'
INTO AuxiliaryTable
FROM myTables
WHERE Conditions are true
ORDER BY Field01
SELECT DISTINCT [Field02] FROM AuxTable
The the results are:

Field02

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

22810
8461760

And what I need is (without showing any other field):

Field02

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

8461760
22810


Is there any good suggestion?
Thanks in advance for any help,
Aldo.

View 3 Replies View Related

How To Write Select Statement Inside CASE Statement ?

Jul 4, 2006

Hello friends,
I want to use select statement in a CASE inside procedure.
can I do it? of yes then how can i do it ?

following part of the procedure clears my requirement.

SELECT E.EmployeeID,
CASE E.EmployeeType
WHEN 1 THEN
select * from Tbl1
WHEN 2 THEN
select * from Tbl2
WHEN 3 THEN
select * from Tbl3
END
FROM EMPLOYEE E

can any one help me in this?
please give me a sample query.

Thanks and Regards,
Kiran Suthar

View 7 Replies View Related

Transact SQL :: Update Statement In Select Case Statement

May 5, 2015

I am attempting to run update statements within a SELECT CASE statement.

Select case x.field
WHEN 'XXX' THEN
  UPDATE TABLE1
   SET TABLE1.FIELD2 = 1
  ELSE
   UPDATE TABLE2
   SET TABLE2.FIELD1 = 2
END
FROM OuterTable x

I get incorrect syntax near the keyword 'update'.

View 7 Replies View Related

How To Use Select Statement Inside Insert Statement

Oct 20, 2014

In the below code i want to use select statement for getting customer

address1,customeraddress2,customerphone,customercity,customerstate,customercountry,customerfirstname,customerlastname

from customer table.Rest of the things will be as it is in the following code.How do i do this?

INSERT INTO EMImportListing ("
sql += " CustId,Title,Description,JobCity,JobState,JobPostalCode,JobCountry,URL,Requirements, "
sql += " IsDraft,IsFeatured,IsApproved,"
sql += " Email,OrgName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,

[code]....

View 1 Replies View Related

Help With Delete Statement/converting This Select Statement.

Aug 10, 2006

I have 3 tables, with this relation:
tblChats.WebsiteID = tblWebsite.ID
tblWebsite.AccountID = tblAccount.ID

I need to delete rows within tblChats where tblChats.StartTime - GETDATE() < 180 and where they are apart of @AccountID. I have this select statement that works fine, but I am having trouble converting it to a delete statement:

SELECT * FROM tblChats c
LEFT JOIN tblWebsites sites ON sites.ID = c.WebsiteID
LEFT JOIN tblAccounts accounts on accounts.ID = sites.AccountID
WHERE accounts.ID = 16 AND GETDATE() - c.StartTime > 180

View 1 Replies View Related

Select Statement Problem - Group By Maybe Nested Select?

Sep 17, 2007

Hey guys i have a stock table and a stock type table and what i would like to do is say for every different piece of stock find out how many are available The two tables are like thisstockIDconsumableIDstockAvailableconsumableIDconsumableName So i want to,Select every consumableName in my table and then group all the stock by the consumable ID with some form of total where stockavailable = 1I should then end up with a table like thisEpson T001 - Available 6Epson T002 - Available 0Epson T003 - Available 4If anyone can help me i would be very appreciative. If you want excact table names etc then i can put that here but for now i thought i would ask how you would do it and then give it a go myself.ThanksMatt 

View 2 Replies View Related

SQL Select Statement To Select The Last Ten Records Posted

Aug 6, 2007

SELECT Top 10    Name, Contact AS DCC, DateAdded AS DateTimeFROM         NameTaORDER BY DateAdded DESC
I'm trying to right a sql statement for a gridview, I want to see the last ten records added to the to the database.  As you know each day someone could add one or two records, how can I write it show the last 10 records entered.

View 2 Replies View Related

Using Select Statement Result In If Statement Please Help

Jul 11, 2007

Hello
How can i say this I would like my if statement to say:  if what the client types in Form1.Cust is = to the Select Statement which should be running off form1.Cust then show the Cust otherwise INVALID CUSTOMER NUMBER .here is my if statement.
<% If Request.Form("Form1.Cust") = Request.QueryString("RsCustNo") Then%> <%=Request.Params("Cust") %> <% Else %> <p>INVALID CUSTOMER NUMBER</p> <% End If%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:RsCustNo %>"
ProviderName="<%$ ConnectionStrings:RsCustNo.ProviderName %>" SelectCommand="SELECT [CU_CUST_NUM] FROM [CUSTOMER] WHERE ([CU_CUST_NUM] = ?)">
<SelectParameters>
<asp:FormParameter FormField="Cust" Name="CU_CUST_NUM" Type="String" />
</SelectParameters>
</asp:SqlDataSource>any help would be appreciated

View 2 Replies View Related

If STATEMENT Within Select Statement Syntax

May 15, 2008

Hi,

I am a newbie to this site and hope someone can help....

I have a select statement which I would like to create an extra column and put an if statement in it.... Current syntax is:

if(TL_flag= '1', "yes") as [Trial Leave]

it is coming up with an error.... I can use Select case but I should not need to as this should work?

Any ideas?

View 2 Replies View Related

Can I Use SELECT Statement To Select First 100 Record????

Apr 21, 1999

I would like to exec a select statement in VB/C++ to return first 100 records? What is the SQL statement should be?

Thanks,

Sam

View 1 Replies View Related

Select Statement With Count Within Another Select

Aug 23, 2013

I am using three tables in this query, one is events_detail, one is events_summary, the third if gifts. The original select statement counted the number of ids (event_details.id_number) that appear per event_name (event_summary.event_name).

Now, I would like to add in another column that counts the number of IDs that gave a gift who attended an event that were also listed in the event_ details table. So far I have come up with the following. My main issue is linking the subquery properly back to the main query. how to count in the sub-query and have the result placed within the groups results in the main query.

SELECT es.event_name, es.event_id, COUNT(ed.id_number) Number_Attendees,
(
SELECT COUNT(gifts.donor_id) AS Count2
FROM gifts
WHERE gifts.donor_id = ed.id_number
) subquery2

[code]....

View 1 Replies View Related

SQL Server 2012 :: Select Statement That Take Upper Table And Select Lower Table

Jul 31, 2014

I need to write a select statement that take the upper table and select the lower table.

View 3 Replies View Related

Using IF...Else Statement SELECT Statement

Sep 7, 2006

 

Hi All,

Can some one point me in the right direction in how to construct my SQL query within my cursor?

I Have got a cursor which i am using to iterate through a table, What i am trying to do is in my statement(used to open the cursor) is compare 2 tables (the one which my cursor is iterating) to see if there is a matching row in the other table (using  both tables ID's Like So:

SELECT column_List
FROM Table1
WHERE Table1_id = Table2_id  


 so for each row  my cursor checks if there is a corresponding match in  table2... but i would like to write to an error log

and do other statements if there is no match

 how do i add this condition to my statement either using an if...else statement proceeding to the next row?

here is the statment i attempted to write:

SELECT column_List
FROM table1
WHERE
 Table1_id = Table2.id

now i want to incoporate the statements below into the statement above as a condition when table1.id <> table2.id    


IF  table1.id <> table2.id    

BEGIN
   SET @DebugMessage = 'data not live.'
   RAISERROR (@DebugMessage, 16, 1) WITH LOG
  END

essentially what i am trying to sayin my statement is:

 go to the first row

check if it has a match in table 2,

 if there is no match execute a number of statements such as error loging e.t.c

go to the next row

 repeat the previous statements 

 

...i also looked through some Case...When statements am just not sure how to put in the condition

thanks in advance

 

View 1 Replies View Related

SQL SELECT Statement

Jul 5, 2006

I am a newbie to SQL.  I have a table (AenComponent) with three columns (State1, State2, State3).  Each column has a set of numeric values.  I would like to get a number count from all of the rows that contain the value of 1, no matter which column they are in.
 
I have tried
SELECT     COUNT(*) AS Expr1FROM        AenComponentWHERE     (State1 = 1) OR (State2 = 1) OR (State3 = 1)
but it does not give me an accurate count.  Any help would be appreciated.
 
thanks
rusty
 

View 4 Replies View Related

Need Help With Select Statement

Dec 29, 2006

I'm trying to get a list of clients and their sum of total pmts, their pmt level, and pmt level description by date range.
Here is what I’ve tried and it will not work. I need to do this without using temp tables.
SELECT C.ClientID, SUM(P.AmountPaid) AS SumOfpmts, tblpmtLevels.pmtLevel, tblpmtLevels.DescriptionFROM         tblPmts AS PL INNER JOIN                      tblPmtReceipts AS P ON PL.PmtID = P.PmtID INNER JOIN                      tblClients AS C ON PL.ClientID = C.ClientID INNER JOIN                      tblPmtLevels ON SUM(P.AmountPaid) >= tblPmtLevels.PmtLevelLow AND SUM(P.AmountPaid) <= tblPmtLevels.PmtLevelHighWHERE     (P.PaymentDate BETWEEN @Start AND @End)GROUP BY C.ClientID
Please provide any help you can, 

View 4 Replies View Related

SQL SELECT Statement

Mar 13, 2007

Hello, Is there a SQL SELECT Statement that can remove the time part in my DataTable. see example below
This is what I have in the first column 0 -   MM/dd/yyyy 12:00:00 AM
This is what I want   -   MM/dd/yyyy
I would rather do it in the SELECT statement instead of doing it in my DataTable using the FORMAT function.
Thanks
Steve

View 5 Replies View Related

Using An SP In A Select Statement

Apr 18, 2007

I have a stored procedure that works like this
getCountryByIPAddress @ipaddr='1.2.3.4'
returns a single 2 char column.
I want to use it in a select statement similar to:
select customername, @country=(exec getCountry @ipaddr=customer.customeripaddress) from customer
I'm intend to receive a list of customer names and the 2 char result of GetCountry based on the customeripaddress field of the customer table.  What I get is a syntax error near Exec and then another one near '.'
Is there another way to accomplish this that I am not seeing?
Ryan
 

View 6 Replies View Related

Select Statement Help

May 29, 2007

Hi,
I am trying to select only the most recent record added to a table per user.  Say the table has a userid, date, and a color and may look like this:
2 5/06/07 red
8 5/3/07 grey
2 5/13/07 green
4 4/30/07 orange
8 4/26/07 yellow
And I want, in any order:
2 5/13/07 green
8 5/3/07 grey
4 4/30/07 orange
 
Thanks for any help.
Greg

View 3 Replies View Related

Help With Select Statement

Jun 19, 2007

Hi, i've run into a problem with a nested query. Consider this:SELECT VehicleRef, Type, Manufacturer, Model, Derivative, isLimited, Term, MilesPA, CH FROM vwVehicles WHERE type='Car' AND manufacturer='Audi' AND model='A3'I get the following results1 Car Audi A3 1.6 Special Edition 3dr 0 2 10000 229.991 Car Audi A3 1.6 Special Edition 3dr 0 2 10000 252.991 Car Audi A3 1.6 Special Edition 3dr 0 3 10000 219.991 Car Audi A3 1.6 Special Edition 3dr 0 3 10000 242.991 Car Audi A3 1.6 Special Edition 3dr 0 2 20000 252.991 Car Audi A3 1.6 Special Edition 3dr 0 2 20000 296.991 Car Audi A3 1.6 Special Edition 3dr 0 3 20000 241.991 Car Audi A3 1.6 Special Edition 3dr 0 3 20000 291.991 Car Audi A3 1.6 Special Edition 3dr 0 2 30000 274.991 Car Audi A3 1.6 Special Edition 3dr 0 2 30000 340.991 Car Audi A3 1.6 Special Edition 3dr 0 3 30000 264.991 Car Audi A3 1.6 Special Edition 3dr 0 3 30000 339.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 10000 227.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 10000 249.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 10000 220.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 10000 244.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 20000 253.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 20000 298.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 20000 244.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 20000 292.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 30000 279.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 2 30000 344.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 30000 267.992 Car Audi A3 1.6 Special Edition Sportback 5dr 0 3 30000 339.99What I need is to only retrieve each vehicleID once, but with the best (lowest) CH price, I also need the term and mileage that corresponds with that price.I tried thisSELECT VehicleRef, Type, Manufacturer, Model, Derivative, isLimited, Term, MilesPA, CH FROM vwVehicles WHERE type='Car' AND manufacturer='Audi' AND model='A3' AND CH = (SELECT MIN(CH) FROM vwVehicles WHERE type='Car' AND manufacturer='Audi' AND model='A3' AND ch >=1 AND ch <=1000)This only returns 1 line though. Is there anyway to get the result I want using one query?Thanks

View 1 Replies View Related







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