Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





WHERE Condition In SELECT Statement


 

Hi All,
I want get the result in a single SELECT statement
 
 SELECT
 SUM (PAID_LOSS),
SUM (PAID_EXP)
GROUP BY COMPANY
FROM VIEW_POLICY
WHERE  Accounting_Period  GE  200701  and LE 200712
-************************************
SELECT
 SUM (MEDICAL_RESERVE)
GROUP BY COMPANY
FROM VIEW_POLICY
WHERE  Accounting_Period  LE 200712
 
 




View Complete Forum Thread with Replies

Related Forum Messages:
If Condition In Select Statement...
Hi,
I need to write an if condition in SELECT statement. Below is the code for the same. But its throwing error. Can some refine the code below.




SELECT tblCustomer.Customer_LegalName,
(IF (tblCustomer.IsNRACustomer = TRUE) SELECT tblCustomer.Customer_PassportNo ELSE
ISNULL(tblCustomer.Customer_TaxId, tblCustomer.Customer_PassportNo)) AS TAXID,

tblCustomer.Customer_DoingBusinessAs, tblSeed_EDDCategory.CategoryName, '2' AS DCS, tblUser_OfficerCode.User_OfficerCode,
tblCustomer.Customer_AreaId, tblCustomer.Customer_BranchId, CONVERT(VARCHAR(11), tblCustomer_EDDCategory.CreateDate)
AS CreateDate, tblSeed_EDDCategory.EDDCategoryId, tblCustomer_EDDCategory.Category_CreateEmpId,
tblCustomer_EDDCategory.CustCatId, tblCustomer.Customer_Id, tblSeed_Area.AreaName, tblSeed_Employee.Name,
tblUser_OfficerCode.User_OfficerName, tblCustomer.Customer_TaxId, tblCustomer.IsNRACustomer,
tblCustomer.Customer_PassportNo
FROMtblCustomer INNER JOIN
blCustomer_EDDCategory ON tblCustomer.Customer_Id = tblCustomer_EDDCategory.CustomerId INNER JOIN
tblSeed_EDDCategory ON tblCustomer_EDDCategory.EDDCategoryId = tblSeed_EDDCategory.EDDCategoryId INNER JOIN
tblSeed_Employee ON tblCustomer.Customer_CreateEmpId = tblSeed_Employee.EmployeeId INNER JOIN
tblUser_OfficerCode ON tblCustomer.Customer_CreateEmpId = tblUser_OfficerCode.EmployeeId INNER JOIN
tblSeed_Area ON tblCustomer.Customer_AreaId = tblSeed_Area.AreaId


Thanks,
Rahul Jha

View Replies !
'IF' Condition On Select Statement?
Can you implement the same type of feature in SQL as MS Access uses with it's "immediate if"
or iif() function? In other words can you look at a specific row and change the contents
of one field based on the contents of another field in the same row?

I am trying to create a view like the the following:

CREATE VIEW AS Test
SELECT
name,
city ,
IF city = 'NY' state ELSE country
FROM address_table

The view's 3rd field will be either [state] or [country] depending on the contents of [city]

Thanks in advance!

..Marisa

View Replies !
Need Help On Select Statement Wit Like Condition
I tried following code and it return no data after query run successfully. I m testing it on msaccess . 
 
SELECT Book.ID, Book.Title, Book.Arthor, Book.Publisher, Book.Year, Book.Price, Inventory.B_ID, Inventory.Quantity
FROM Book INNER JOIN Inventory ON Book.ID=Inventory.B_ID
WHERE Book.ID=Inventory.B_ID And ("Book.Arthor" Like '%es%');


-------

I have test and test2 in Arthor column ... Thanks all !!
 

View Replies !
Condition In Select Statement
col1          col2 col3   col4

36930.60   145    N   . 00
17618.43   190   N    . 00
6259.20    115    N    .00
8175.45     19    N     .00
18022.54   212   N    .00
111.07      212   B     100
13393.05   67   N     .00


In above 4 col

if col3 value is B then cursor has to fectch appropriate value from col4.
if col3 value is N then cursor has to fectch appropriate value from col1.
and also wants the sum of result above conditions when column 3 has two values(i.e N,B) for single col2 value
 
here col2 values are unique
 
take an example for col2=212
if col3=B
  then result is 100
if col3=N
then result is 18022.54
for  a single col 2 value ,if col3= N and B then we want sum of above 2 conditions i.e (100+18022.54)
but not the sum of (100+18022.54+111.07+0.0) .

 
Can any one reply for this..............
 

View Replies !
How To Put Condition In Select Statement To Write A Cursor
col1          col2 col3   col4
36930.60   145    N   . 00
17618.43   190   N    . 00
6259.20    115    N    .00
8175.45     19    N     .00
18022.54   212   N    .00
111.07      212   B     .00
13393.05   67   N     .00
In above 4 col
if col3 value is B then cursor has to fectch appropriate value from col4.
if col3 value is N then cursor has to fectch appropriate value from col1.
here col2 values are unique.

Can any one reply for this..............

View Replies !
Like Condition In Sql Statement
This is my sql query

Select DOJ AS 'JoiningDate' from emp where DOJ like '%2008/09/04%'

there are 8 records on this time.But it displays no result .
The column is datetime datatype
year month date or we need to mention any thing other than this.

 
 

View Replies !
Hi, How Could Put A Condition In Statement.
Hi, i wanted to put a condition based on my codes below.. but where i had to put the condition? like where QTY=3
please help..

INSERT INTO magpatoc.dbo.RSOTransfer(RSONO, Customer, ItemCode, ItemDescription, Source, MOQ, QuantityRequired, Remarks, ZeroStock, NewProduct, ProjectForecast, WithMotherPO, Other, RequestedBy, RequestedDatetime, NotedBy, RecievedBy, RecievedDatetime, PreparedBy, PreparedDatetime, ApprovedBy, ApprovedDate, ReservationNoDate, PurchaseOrderNo)
SELECT * FROM OPENROWSET ('Microsoft.Jet.OLEDB.4.0','c:CopyOfRSODB.mdb';'admin';'',FinalCustItemRSO)


ed9teenMagnaza

View Replies !
Derived Column From A Condition Statement
I've found that there is no such thing as a Case Statement in the Derived Column task in the data flow objects.  I've written a ternary statement instead.  I can't seem to get it to work exactly how I want it to. For example

AccountCategory == "E" ? 1 : 2

Works fine but the following doesn't

AccountCategory == "E" ? CreditAmount : DebitAmount

The CreditAmount and DebitAmount Fields are spelled correctly, the field type of AccountCategory is String and the Field type of CreditAmount and DebitAmount is numeric, but that seems to be the same situation that I have in the first example that works.  Am I missing something?  I'd appreciate any advice anyone has to offer.  Thanks,

Bill

View Replies !
UPDATE Statement With A JOIN Condition
Hi all,

HERE IS MY UPDATE STATEMENT:

Update WACTS_Inventory_Part_Loc_Tbl SET WIPLT_Part_New_Qty = WIPLT.WIPLT_Part_New_Qty + tmp.MATIN_QTY FROM

WACTS_Inventory_Part_Loc_Tbl WIPLT

INNER JOIN

Temp_MatIn_Data tmp

ON

WIPLT.WIPLT_Part_Number_MSBA=tmp.PARTS_ShortID

WHERE

WIPLT.WIPLT_Location_Code='MF'

 

I have a Problem with this satment becoz my Temp_Matin_Data_Tmp table contains two records with the same PartNumber that is (ShortId) and the two records have two different quantities.

The WACTS_Inventory_Part_Loc_Tbl has only one Part NUmber Record and the key is the PartNUmber and Location_Code.

 

Now when the Update Satement runs it updates the qty only from the first record of the temp table and does not update the quantity of the second record from tne source table.

I woould appreciate any help on this.

 

Thanks,

Jothi

 

View Replies !
SELECT UNION SELECT Condition
let say i got such condition

INSERT INTO TABLE
SELECT
WHERE XX NOT EXISTS (SELECT 1 FROM TABLE)
UNION
SELECT
WHERE XX NOT EXISTS (SELECT 1 FROM TABLE)

do you think that mssql will produce error or problem?
from what i heard it will.

View Replies !
Select Condition From Log Table
Hi guys

Im not even sure how to word this right, but how do I compare one element(unsure word number 1) namely Filename, from a list of results, and use that value as a variable for another condition in the same select... I think?!

So if I get a list of 50 filenames (from a log table), some might be double.
If the file was successfully processed, it will log that filename and the status as OK and if not then BAD.
The file will be modified and then reprocessed until OK. Each time the file was processed, it will log the filename and status.
I then run a statement that shows all the files that were BAD (from the log table) and it will bring up then filename and BAD status.
What I want to do is check the status' and if the file is BAD, check if there is another logged entry with that filename and status is OK, if found then not produce output as Im only looking for the files that status' are BAD with no OK status for any of the logged entries for that filename.

Is that understandable? If not then Ill try reword it.

The help is much appreciated!
Justin

View Replies !
Condition In Select Query
create function stzipcustinfo

( @campaign varchar(50), @startdate datetime, @enddate datetime,@audience_type char(10) )


RETURNS TABLE

AS

RETURN


(Select distinct t.campaign,t.Sopnumbe,t.Custnmbr,t.Custname,

t.Address1,t.Address2,t.City,t.State,t.Country,t.Zipcode, t.Phone,sum(t.totalquantity) as Totalquantity,

t.Audience_type

from

(

select distinct

v.sopnumbe, v.campaign, v.custnmbr, v.custname, v.address1, v.address2,v.city,v.state,v.country,v.zipcode,

v.Phone, v.totalquantity as totalquantity,


case @audience_type

when v.custclas then v.custclas

end as audience_type
from vwstzipcustaudienceinfo v

Where (v.itemnmbr = '' or v.itemnmbr=v.itemnmbr) and v.Campaign = @Campaign and (v.docdate between @startdate and @enddate)


) as t

where t.audience_type is not null

group by t.campaign,t.Sopnumbe,t.Custnmbr,t.Custname,

t.Address1,t.Address2,t.City,t.State,t.Country,t.Zipcode, t.Phone, t.Audience_type

)

--select * from mystatezipcustaudienceinfo('cpd','1/1/2008','5/15/2008','INDPATIENT') --getting 500rows

--select * from mystatezipcustaudienceinfo('Cpd'','1/1/2008','5/15/2008','INST-HOSPITAL') -- note getting single row

problem have a “-“ in them..i m not getting result..so what condition should be in red color one..


thanks

View Replies !
Select Statement Within Select Statement Makes My Query Slow....
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 Replies !
T-SQL: Different SELECT Executed Depending On Condition.
I'm trying to execute a different SELECT statement depdning on a certain condition (my codes below). However, Query Analyzer complains that 'Table #Endresult already exists in the database', even though only one of those statements would be executed depending on the condition. Any ideas as to a work around? I need the result in an end temporary table.


IF @ShiftPeriod = 'Day'
SELECT * INTO #EndResult FROM #NursesAvailable WHERE CanWorkDays = 1
ELSE IF @ShiftPeriod = 'Night'
SELECT * INTO #EndResult FROM #NursesAvailable WHERE CanWorkNights = 1
ELSE IF @ShiftPeriod = 'Evenings'
SELECT * INTO #EndResult FROM #NursesAvailable WHERE CanWorkEvenings = 1
ELSE
SELECT * INTO #EndResult FROM #NursesAvailable

View Replies !
How To Select Train Data With Condition
Hi, in SQL Management Studio, we just click 'Process' to train the data, how could I conditionally select a subset of Data Source (View) to train?

Thanks in advance.
Ricky.

View Replies !
If Condition Within Select Query Sql Server 2000
Hi all,
 
I have to write a select query which need some logic to be implemented.
Query is like
select name,number,active,
if active ="true" then
select @days=days from tbl_shdsheet
else
@days=''
end
from tbl_emp
 In the above query there will be days row for that employee if active is true else there won't be any data for that emp in the tbl_shdsheet
So how can i write queery for this.

View Replies !
Update Statement Performing Table Lock Even Though Where Condition On Clustered Primary Index?
Hi All,I have a database that is serving a web site with reasonably hightraffiic.We're getting errors at certain points where processes are beinglocked. In particular, one of our people has suggested that an updatestatement contained within a stored procedure that uses a wherecondition that only touches on a column that has a clustered primaryindex on it will still cause a table lock.So, for example:UPDATE ORDERS SETprod = @product,val = @valWHERE ordid = @ordidIn this case ordid has a clustered primary index on it.Can anyone tell me if this would be the case, and if there's a way ofensuring that we are only doing a row lock on the record specified inthe where condition?Many, many thanks in advance!Much warmth,Murray

View Replies !
HELP With SQL Query: Select Multiple Values From One Column Based On &&<= Condition.
Hello all.  I hope someone can offer me some help.  I'm trying to construct a SQL statement that will be run on a Dataset that I have.  The trick is that there are many conditions that can apply.  I'll describe my situation:
 
I have about 1700 records in a datatable titled "AISC_Shapes_Table" with 49 columns.  What I would like to do is allow the user of my VB application to 'create' a custom query (i.e. advanced search).  For now, I'll just discuss two columns;  The Section Label titled "AISC_MANUAL_LABEL" and the Weight column "W".  The data appears in the following manner:
 
(AISC_Shapes_Table)
 
AISC_MANUAL_LABEL          W
W44x300                               300
W42x200                               200
(and so on)
WT22x150                             150
WT21x100                             100

(and so on)
MT12.5x12.4                          12.4
MT12x10                               10
(etc.)
 
I have a listbox which users can select MULTIPLE "Manual Labels" or shapes.  They then select a property (W for weight, in this case) and a limitation (greater than a value, less than a value, or between two values).  From all this, I create a custom Query string or filter to apply to my BindingSource.Filter method.  However I have to use the % wildcard to deal with exceptions.  If the user only wants W shapes, I use "...LIKE 'W%'" and "...NOT LIKE 'WT%" to be sure to select ONLY W shapes and no WT's.  The problems arises, however, when the user wants multiple shapes in general.  If I want to select all the "AISC_MANUAL_LABEL" values with W  <= 40, I can't do it.  An example of a statement I tried to use to select WT% Labels and MT% labels with weight (W)<=100 is:
 



Code SnippetSELECT     AISC_MANUAL_LABEL, W
FROM         AISC_Shape_Table
WHERE     (W <= 100) AND ((AISC_MANUAL_LABEL LIKE 'MT%') AND (AISC_MANUAL_LABEL LIKE 'WT%'))
 
 

 It returns a NULL value to me, which i know is NOT because no such values exist.  So, I further investigated and tried to use a subquery seeing if IN, ANY, or ALL would work, but to no avail.  Can anyone offer up any suggestions?  I know that if I can get an example of ONE of them to work, then I'll easily be able to apply it to all of my cases.  Otherwise, am I just going about this the hard way or is it even possible?  Please, ANY suggestions will help.  Thank you in advance.
 
Regards,
 
Steve G.
 
 
 
 

View Replies !
Multiple Tables Used In Select Statement Makes My Update Statement Not Work?
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 Replies !
Using Conditional Statement In Stored Prcodure To Build Select Statement
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 Replies !
TSQL - Use ORDER BY Statement Without Insertin The Field Name Into The SELECT Statement
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 Replies !
Can I Print The Results Of A Condition Based On The Condition?
For example..

select * from mytable where MyNum = 7

If this brings back more than 1 row, I want to display a message that says,

Print 'There is more than one row returned'

Else (If only 1 row returned), I don't want to print anything.

Can I do this? Thx!

View Replies !
COndition Spli - Error Date Condition
Dear friends,

I'm having a problem... maybe it's very simple, but with soo many work, right now I can't think well...

 

I need to filter rows in a dataflow...

I created a condition spli to that... maybe there is a better solution...

And the condition is: Datex != NULL(DT_DATE)

(Some DATE != NULL)

 

 

[Eliminar Datex NULL [17090]] Error: The expression "Datex != NULL(DT_DATE)" on "output "Case 1" (17123)" evaluated to NULL, but the "component "Eliminar Datex NULL" (17090)" requires a Boolean results. Modify the error row disposition on the output to treat this result as False (Ignore Failure) or to redirect this row to the error output (Redirect Row).  The expression results must be Boolean for a Conditional Split.  A NULL expression result is an error.

 

What is wrong??

Regards,

Pedro

View Replies !
How To Write Select Statement Inside CASE Statement ?
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 Replies !
Help With Delete Statement/converting This Select Statement.
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 Replies !
Select Statement Problem - Group By Maybe Nested Select?
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 Replies !
SQL Select Statement To Select The Last Ten Records Posted
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 Replies !
SELECT Query - Different Columns/Number Of Columns In Condition
I am working on a Statistical Reporting system where:


Data Repository: SQL Server 2005
Business Logic Tier: Views, User Defined Functions, Stored Procedures
Data Access Tier: Stored Procedures
Presentation Tier: Reporting ServicesThe end user will be able to slice & dice the data for the report by


different organizational hierarchies
different number of layers within a hierarchy
select a organization or select All of the organizations with the organizational hierarchy
combinations of selection criteria, where this selection criteria is independent of each other, and also differeBelow is an example of 2 Organizational Hierarchies:
Hierarchy 1


Country -> Work Group -> Project Team (Project Team within Work Group within Country) 
Hierarchy 2


Client -> Contract -> Project (Project within Contract within Client)Based on 2 different Hierarchies from above - here are a couple of use cases:


Country = "USA", Work Group = "Network Infrastructure", Project Team = all teams
Country = "USA", Work Group = all work groups

Client = "Client A", Contract = "2007-2008 Maint", Project = "Accounts Payable Maintenance"
Client = "Client A", Contract = "2007-2008 Maint", Project = all
Client = "Client A", Contract = allI am totally stuck on:


How to implement the data interface (Stored Procs) to the Reports
Implement the business logic to handle the different hierarchies & different number of levelsI did get help earlier in this forum for how to handle a parameter having a specific value or NULL value (to select "all")
(WorkGroup = @argWorkGroup OR @argWorkGrop is NULL)

Any Ideas?  Should I be doing this in SQL Statements or should I be looking to use Analysis Services.

Thanks for all your help!

View Replies !
Using Select Statement Result In If Statement Please Help
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 Replies !
If STATEMENT Within Select Statement Syntax
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 Replies !
Can I Use SELECT Statement To Select First 100 Record????
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 Replies !
Using IF...Else Statement SELECT Statement
 

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 Replies !
SQL Select Statement
I have a database that is constantly being added to... what im trying to do is select the 10 most recent entries EXCEPT for the very most recent.
Selecting the 10 most recent is something I can do.... 'select top 10 * from tablename order by id desc' - but how do I leave out the most recent?
SQL Server 2005

View Replies !
SELECT Statement
Hi,I'm sorry for the lame question, but I''m a newbie at C#.With the code that follows my signature, I'm trying to retrieve a single value from a table.The query is ok, I've tested manually.But I get the error:"The name userPassword does not exist in the current context".I realize it's a matter of scope, but I need to have the variable value available there.Furthermore, I think that I'm getting no result from the database with my code, because if I put the Response.Write(userPassword) line inside the while cicle, nothing is displayed.Any help would be appreciated.Warm Regards,Mário Gamito--SqlConnection myConn = new SqlConnection("user id=sa" + "password=secret" +  "server=192.168.1.4" + "database=workers");try{myConn.Open()}catch (Exception e){Console.WriteLine(e.ToString());}try{SqlDataReader myReader = null;SqlCommand myCommand = new SqlCommand("SELECT password FROM dbo.users WHERE email = 'gamito@foobar.lan'", myConn);myReader = myCommand.ExecuteReader();while(myReader.Read())  {     string userPassword = myReader["password"].ToString());  }}catch (Exception e){ Console.WriteLine(e.ToString());}myConn.Close();Response.Write(userPassword);

View Replies !
Max Select Statement
Hi Guys,
                           Having a little problem,
                          can someone take a look at this... Thank You...
                          Trying to get the   Max(WebNameTitle)  From Max(NumerID)  
  
                          Example code below throws error : I need the Max Value from the Column( WebNameTitle <---nvarchar) and the Max Value from the Column (NumberID  <--int)
                             
                                                  New SqlCommand("Select Max(WebNameTitle) FROM ComBooks WHERE Max(NumberID) = MaxNumberID", conCommerce)
 
 

View Replies !
Select Statement In ASP.NET
hello all,
I need to SELECT data in my ASP.NET web service from my MSSQLExpress
database. I checked to INSERT data into it and it worked well , and
here is the code of my insert: 1 <WebMethod()> _2 Public Function SaveNumName(ByVal UserNum As Integer, ByVal UserName As String)3 Dim DS As New SqlDataSource4 5 DS.ConnectionString = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=tstSQL"6 ' DS.ConnectionString = ConfigurationManager.ConnectionStrings("tstSQLConnectionString1")7 DS.InsertCommandType = SqlDataSourceCommandType.Text8 DS.InsertCommand = "insert into tbl1 (number,name) values (@number,@name)"9 DS.InsertParameters.Add("number", UserNum)10 DS.InsertParameters.Add("name", UserName)11 12 DS.Insert()13 14 Return 115 End Function The previous code worked well for the insertion of data, but when I tryed the same technique with the selection of data, it didn't work, and here is my code for the select: 1 <WebMethod()> _2 Public Function GetName(ByVal Number As Integer)3 Dim Name As String4 'Dim ConnStr As String = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=malalation_tstSQL"5 Dim GV As New GridView6 GV.Visible = False7 Dim DS As New SqlDataSource8 DS.ConnectionString = "Data Source=.SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=tstSQL"9 10 DS.SelectCommandType = SqlDataSourceCommandType.Text11 DS.SelectCommand = "SELECT name from tbl1 where number = 1"12 ' DS.Select()13 GV.DataSource = DS14 Name = GV.Rows(0).Cells(1).Text15 Return Name16 End Function
  I think that the problem is with storing the result of the SELECT satatement, so what do you think??   

View Replies !
Need Help With SELECT Statement
Hi, I have a table (SQL 2000) that holds inside login records of each system. All the systems logging 0-50 times each day.
I need to create “Last Login� report that shows as following:
SystemID                     LastLogin
System001                   2008-04-23 21:14:49
System002                   2008-03-12 21:15:06
System003                   2008-01-20 22:14:15
System004                   2008-04-23 22:14:24
System005                   2008-02-23 22:14:42 
Need help with SELECT statement 
Thanks in advance.
Alex
 

View Replies !
Select Statement
Hi Guys,
I have some problem with sqlquery can any one help? Here is my statement
strSQL=strSQL & "employee= "Select empname from tbl_emp where empname= strUname"
 when executing it says Expected end of statement
Thanks
 

View Replies !
Select Statement Help
 Hello I only need to get the row from InvoiceHeader where branchID = 116The problem is I'm also getting the rows from InvoiceDetail where branchID is stored how will I solve this?  Here's the code. SelectBranch.BranchLocation,Receipt.InvoiceNo,Receipt.AmountPaidFrom ReceiptINNER JOIN InvoiceHeader ON Receipt.InvoiceNo = InvoiceHeader.InvoiceNoINNER JOIN InvoiceDetail ON InvoiceHeader.InvoiceNo = InvoiceDetail.InvoiceNoINNER JOIN Branch ON InvoiceDetail.BranchID = Branch.BranchIDWhereBranch.BranchID = 116 

View Replies !
Select Statement
Hi all,Can u plz tell me what is wrong with this select statement
"select sku from products where cat='" & catitems.SelectedValue.Replace("'", "''") & "' and subcat is nothing"
plz help regards

View Replies !
Help Me With A SELECT Statement, Please
hello
i have two tables: ProductComments (CommentID, ProductID, UserName, Comment, Date) and Users (UserName, City, Age)
i need to SELECT * FROM ProductComments where ProductID = @ProductID, and select from Users Table  info about the users who commented
i need some help, because i'm not so good at SQL yet:(
thank you

View Replies !
Select Statement
The following Select statement shows "distinct l.userid" for the available c.id.  I would like to see all the "c.id" even if "distinct l.userid" are NULL. 
select c.id, count(distinct l.userid) from Companys c
left join labvalues l on c.id = l.companyid
where l.labdate>='01/01/2007' and l.labdate <'02/01/2007' and
c.id in (1,2,3,4,5,6,7)
Output: 1     12
            2     13
            7      25
Expected Output:  1     12
                            2    13
                            3     NULL
                            4     NULL
                            5     NULL
                            6     NULL
                            7     25
PLEASE HELP......

View Replies !
Need Help With This Select Statement
I have a table called fund and a another table called FundPerformance.. and they both are linked together using FundId..
 
But suppose if a fund doesnt have any performance information.. It doesnt have a entry in the FundPerformance table but has a entry in the Fund table...
I have written select statement that would give me the results.. But suppose if that particular fund is not present in the fundperformance table that fund doesnt show up in the select query..
So how can i get it.. I tried Inner Join, Left Outer Join and Right Outer join but it doesnt show up at all.SELECT
pf.FundId,
dbo.udf_Quarter(Getdate()) PeriodId,
f.FundName,
CASE
WHEN
pf.PlanFundDisplayName IS NULL
THEN
f.ShortName
ELSE pf.PlanFundDisplayName
END FundNames,
f.InvestmentPolicy,
f.FundClassCd,
c.ClassName,
c.ClassDefinition,
p.YearToDate,
p.OneYear,
p.ThreeYear,
p.FiveYear,
p.TenYear,
p.SinceInception,
f.ExpenseRatio,
f.PortfolioManager,
f.AssetAllocationCashPercent CashAllocPct,
f.AssetAllocationEquityPercent EquityAllocPct,
f.AssetAllocationConvertiblesPercent ConvertAllocPct,
f.AssetAllocationFixedIncomePercent FixedIncAllocPct,
f.AssetAllocationOtherPercent OtherAlloc,
p.TotalNetAssets,
p.AsOfDate
FROM
PlanFund pf
Right Outer JOIN Fund f
Right Outer JOIN FundClass c
ON f.FundClassCd = c.FundClassCd
Right Outer Join FundPerformance p
on f.FundId = p.FundId
ON f.FundId = pf.FundId
--Left Outer JOIN FundPerformance p
--ON pf.FundId = p.FundId
WHERE
pf.PlanId = @PlanId
AND
p.PeriodId = dbo.udf_Quarter(Getdate()) --PeriodId --@PeriodId

ORDER BY
pf.FundDisplayOrder
 any help will be appreciated
Regards,
Karen

View Replies !
SQL Select Statement
What is the syntax for a select statement within the controls of a label, or text box, I’m using VB? Thanks

View Replies !
Regarding Select Statement
How to select two different fields from two different tables depending on the ID in a query.
For Example:
A from table1 and c from table 2 must be selected depending on the ID of table1 and Id of table2.
please help me.

View Replies !
Help Me With A SELECT Statement Please
hello
i am trying to make a select statement between two tables and i don't know how to start doing that
i have two tables:
UserComments where i store each comment made by all users
and the Pictures table, and in one of his rows "LastComment" i store the userName -varchar(255)- of the user who last commented that picture
i need to make a select statement with one input parameter (userName of the logged in user) and two output parameters(int) (@totalComments - would come from the UserComments table, and @lastComments - would come from the Pictures table)
@totalComments - i need to COUNT how many comments that user has made from the UserComments
@lastComments - count at how many pictures that user is last commenter from the Pictures
there is no relation between these two tables, i can make two stored procedures one for each COUNT but i think is stresfull for the database
please help me, thanks

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved