WHERE Statement On Two Tables?

May 26, 2008

How do I do a WHERE statement on two tables?

CREATE TABLE [Audit]
(
[AuditID] [int],
[AuditDate] [datetime]
)

CREATE TABLE [ToDoItem]
(
[ToDoItemID] [int],
[AuditID] [int],
[DueDate] [datetime],
[CompletedDate] [datetime]
)

What I need to do is select all Audits that
still have ToDoItems not complete
that the DueDate has passed
or where the audit was done over six months ago

What I tried is

SELECT
[AuditID]
FROM
Audit a
WHERE
(a.AuditID in (SELECT AuditID
FROM ToDoItem t
WHERE
t.CompletedDate is null
AND (t.DueDate < getDate()
or ( (DateAdd(Month, 6, < a.AuditDate)) < getDate()) )
))


----
Dave

View 6 Replies


ADVERTISEMENT

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

SQL Statement Joining Tables Help

Jun 29, 2006

I have created a join statement with 3 tables in my database. The join wokers fine but the result is not on the format (Layout) I need it. Here is where I need help. Let me explain what I need to accomplish.
I have 3 tables in my database
1- Rates (Master Table)
Every Prepaid long distance card have a list of countries with individual rates
2- Countries_Template (Child table used to get the country name)
This table is to get copy of a list of countries every time a new card's rate is created
3- Card_Denominations (Child table where I create all the price denominations of each card)
Each cards have multiple cards denominations ($2, $5, $10, $20 and so on) so every time a card is inserted in the Cards table I insert the card denominations on the Card_Denominations table.
The format I need to return from my Query using above 3 tables have to look like this:
Flag   Country   Rate       $2      $5      $10      $20
pic     USA         .20       500    750   1200     1700
 
Please help
Tia
Charles
---------Join Statement -----------------
Select Rates.Card_Id, Rates.Country_Id, Rates.Flag,      Countries_Template.Country_Name,       Card_Denominations.Card_DenominationFrom RatesRight Join Countries_TemplateOn Rates.Country_Id = Countries_Template.Country_IdRight Join Card_DenominationsOn Rates.Card_Id = Card_Denominations.Card_IdWhere Rates.Card_Id = 1
---------------------------------------------

View 1 Replies View Related

SELECT Statement For 2 Tables

May 8, 2004

Hi
How do I make a SELECT statement to use in WebMatrix to access data that selects from 2 tables:
based on LastnameID it selects from table Contacts
and based on first name and Lastname it selects from student tables
regards
daniel

View 1 Replies View Related

SQL, Temp Tables And The Like Statement

Jul 23, 2005

I have a stored procedure which contains a temp table called #NamesThis has n rows of values which are peoples names (they are varchars)i.e#NamesRickRobFrankI have a table called tblPeople.tblPeopleid Name Telephone1  Ric    012334213452  Robert 0321120931233  Paul  123 123 123 123 I want to find all the people in tblPeople whose names are like those in the temp table #NamesHow do I do this?

View 1 Replies View Related

Update Two Tables With The Same Statement

Sep 16, 2005

hi,does any know how to update two tables with the same statement?is it possible?here is my unsuccessful try:UPDATE A,BSET A.VAL='BLUH1', B.VAL='BLUH2'from #T A, #T2 BWHERE  A.LOANID=B.LOANID

View 3 Replies View Related

SELECT Statement Between Two Tables

Jan 28, 2005

I have two tables

Absent
==========
absent_id
employee

Employee
==========
emp_id
employee
department

In plain english I want to select * from absent where the employee's department (in the employee table) equals 'whatever'

Can anyone help please.

View 2 Replies View Related

MERGE Statement Into Two Tables

Aug 21, 2012

I am trying to update values in two tables (approx 1-2 million records).

I have decided to use a MERGE statement, however have been unsuccessful to do so.

Below is an example of the statement.

The error is receive is "Incorrect syntax near '('." right after the MERGE line.

Is it not possible to use this syntax ?

Example:
[CODE]
MERGE
( SELECT a.id, b.id2
FROM TableA A
JOIN TableB B

[Code]....

View 5 Replies View Related

Update 2 Tables In One Statement

May 1, 2008

this code is not working.
I can’t update 2 tables in one statement?

update pd, p
set pd.show = 0 , pd.seashow = 0
FROM ProductDetail pd
join Products p on p.itemid = pd.ItemID
where pd.show = 1
and pd.site in (1,4,6)

View 3 Replies View Related

Joining 3 Tables In Statement

Jan 15, 2015

I have 3 tables that I'm trying to joing together in an SQL statement. I've tried several different JOIN statements, but can't seem to get it to work correctly.

Scenario:

I want all records from TABLE_1
I want to LEFT JOIN TABLE_1 to TABLE_2, but I only want records from TABLE_2 that are an 'Active' STATUS. My problem is, the STATUS field is in TABLE_3.

I have to link TABLE_1 to TABLE_2 by ITEMNUM.
I have to link TABLE_2 to TABLE_3 by ORDERNUM since TABLE_3 does not have ITEMNUM, and pull across the STATUS.

TABLE_1 is an ITEMID table. TABLE_2 is our ORDER_LINE table, and TABLE_3 is our ORDER_HEADER info. I want all items listed; then I'd like to see all items that are on an order (TABLE_2), but only if the ORDER_HEADER (TABLE_3) is an 'ACTIVE' STATUS.

View 10 Replies View Related

How Can I Run Select Statement For Two Tables That

Jul 2, 2007

Hi all,
How can I run select statement for two tables that are on two different databases?


Let's say I have a SQL server 2005 on Windows 2003 server.
On this SQL server 2000 I have two databases.
Let’s say DB1 and DB2. On db1 I have Tbale1 and on DB2 I have Table2.

I like to run a select statment:
Select Table1.*, Table2.* from Table1, Table2
Where table1.id = Table2.id
And Table1.user_name like '%jim%'

Both tables have same architecture.



Thanks for any help.


Abrahim

View 2 Replies View Related

Inserting Into Two Tables With One Sql Statement

Jul 20, 2005

Anyone who can help,I have two tables T1 and T2. T1 has fields K1 and F2 and T2 has fieldsK2 and F1. F1 is the foreign key relating to K1 and F2 is the foreignkey relating to K2.My initial question has been how can I add a row to both tables withaccurate Fx values in one SQL INSERT statement? I have been told itcannot be done.If it can be done in one statement, what is that statement?If it cannot be done in one statement, how can it be done in the leastnumber of statements?Thanks,Greg the SQL student

View 4 Replies View Related

Select Statement Help:How Do I Query Two Tables

Mar 20, 2006

How do I Query two tables and minus the result to be displayed in a gridview.  I will appreciate all the help that I can get in this regard. Find below my two select statement
1st Select StatementDim SelectString As String = "SELECT DISTINCT [Course_Code], [Course_Description], [Credit_Hr], [Course_Type], [Course_Method] FROM [MSISCourses] WHERE (([Course_Type] = Core) OR ([Course_Type] = Information Integration Project) "If radBtnView.Checked = True ThenSelectString = SelectString & " OR ([Course_Type] = 'Knowledge')"End IfIf chkGView.Checked = True ThenSelectString = SelectString & " OR ([Specialization] = 'Data Management')"End IfIf chkGView2.Checked = True ThenSelectString = SelectString & " OR ([Specialization] = 'General')"End IfIf chkGView1.Checked = True ThenSelectString = SelectString & " OR ([Specialization] = 'Electronic Commerce')"End IfIf chkGView3.Checked = True ThenSelectString = SelectString & " OR ([Specialization] = 'Network Administration and Security')"End IfIf chkGView4.Checked = True ThenSelectString = SelectString & " OR ([Specialization] = 'Healthcare Information Systems')"End IfSqlDataSource3.SelectCommand = SelectString
2nd Select Statement"SELECT DISTINCT [Co_Code], [Co_Description], [Cr_Hr], [Co_Type], [Co_Method] FROM [StudentCourses] WHERE ([Co_Code] = StdIDLabel)"
my gridview<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="Course_Code" DataSourceID="SqlDataSource3" GridLines="Horizontal"><Columns><asp:BoundField DataField="Course_Code" HeaderText="Course_Code" ReadOnly="True" SortExpression="Course_Code" /> <asp:BoundField DataField="Course_Description" HeaderText="Course_Description" SortExpression="Course_Description" /> <asp:BoundField DataField="Credit_Hr" HeaderText="Credit_Hr" SortExpression="Credit_Hr" /> <asp:BoundField DataField="Course_Type" HeaderText="Course_Type" SortExpression="Course_Type" /> <asp:BoundField DataField="Course_Method" HeaderText="Course_Method" SortExpression="Course_Method" /> </Columns></asp:GridView>

View 6 Replies View Related

Listing Tables From A Filegroup Using Sql Statement

Jul 30, 2001

Hi everybody,
Is there anyway we can find the list of tables in each filegroups by writing a sql query..

Thanks
muthu

View 1 Replies View Related

INSERT Statement Involving Different Tables

May 11, 2007

I have three tables:

1. RubricReport 2. RubricReportDetail and 3. RubricReportTemplate

RubricReportDetail has columns ReportID and Age
RubricReportTemplate has columns IndicatorID and Salary


I want to insert a row in RubricReport Table with ReportID = @ReportID (RubricReportDetail) and IndicatorID = @IndicatorID (of RubricReportTemplate). How can I do this?

Kindly help me with this. Thanks in advance.

View 1 Replies View Related

Update 2 Tables In Single Statement

Mar 13, 2008

Is it possible to update 2 tables in a single t-sql statement?

If Yes, whats the syntax?


Update Table1,Table2 ... is not working

View 2 Replies View Related

How To Join Tables From Different Databases In SQL Select Statement?

Apr 30, 2008

I have a basic sql statement, where I have a usersID, and I want to joing that usersID to another table in another database to get the users first and last names.  How do I join across databases... each with a different connection string? 
 Here's what I want..
Select usersID from tableA in databaseA, and usersFirstName, usersLastName from table B in database B where the usersID from tableA = the usersID in tableb. 

View 6 Replies View Related

Joining Tables In A VIEW SELECT Statement

Jan 11, 1999

Wuddup,

I am trying to create a view that encapsulates some specific info from many different tables. I have about 30 tables all with exactly the same field names and field types. I want to take 3 of the fields from every table and put them together into one 'VIEW' so I can run more efficient queries. SQL however, doesn't let you 'combine' 2 columns from different tables into one column in the view. (making sense?)
I tried running a 'UNION' but you are specifically NOT allowed to run a union in a create view statement. Anyone have any ideas?

View 1 Replies View Related

Single Statement To Delete Record Into More Tables

Aug 6, 2004

Hi ,

I little question for you ... is it possibile to write a SQL statement to delete records in several tables at the same time?

For example if I've two tables involved by join

DELETE <...> from Customers A
INNER JOIN CustomerProperties B ON A.CustomerID=B.CustomerID

I Must use two statement to remove records from both the tables?

Thx

View 3 Replies View Related

Creating A Select Statement With Subqueries To 3 Other Tables...

Jul 23, 2005

I have four total tables.Table One (Documents)- List of Documents. Each record has two fieldsrelated to this issue. First field (Document_ID) is the ID of thedocument, second field is the ID of the record (Task_ID) it isassociated to in Table Two.Table Two (Activities)- List of activities. Each record has two fieldsrelated to this issue. First field (Activity_ID) is the ID of theactivity, the second field (Group_ID) is the ID of the record it isassociated to in Table Three.Table Three (Groups) - List of groups. Each record has two fieldsrelated to this issue. First field (Group_ID) is the ID of the group,the second field (Stage_ID) is the ID of the record it is associated toin Table four.Table Four (Stages)- List of Event Stages. Each record has two fieldsthat is related to this issue. The first field (Stage_ID) is the ID ofthe stage of an event, the second record is the ID number associated tothe event. This last ID is a known value.20000024 = the Event IDI'm trying to come up with a list of Documents from the first tablethat is associated to an Event in the Fourth table.Query Analyzer shows no errors within the script. It just doesn'treturn any data. I know that it should, if it does what I'm wanting itto do.SELECT Document_ID FROM Documents as A where ((SELECT Event_ID FROMStages as D WHERE (D.Stage_ID = (SELECT Stage_ID FROM Groups as C WHERE(C.Group_ID = (SELECT Group_ID FROM Activity as B WHERE (B.Activity_ID= A.Activity_ID))))))= '20000024')

View 2 Replies View Related

UPDATE Statement Involving Tables In Different Databases

Feb 22, 2006

I want to create an UPDATE statement that updates a value in a table indatabase A based on the results of an inner join between tables eachresiding in deifferent databases.What is the correct syntax for doing this?The following should give you an idea of what I'm trying to do:UPDATE A.dbo.tblCarsSET A.dbo.tblCars.Car = 'Ferrari'FROMA.dbo.tblCars INNER JOIN B.dbo.tblHouses ONA.dbo.tblCars.RecID = B.dbo.tblHouses.RecIDWHERE (B.dbo.tblHouses = 'Mansion')

View 7 Replies View Related

Transact SQL :: How To Use A Between In Case Statement For Joining 2 Tables

Jul 27, 2015

below is the sql query i am trying to write and i receive an error saying Incorrect syntax near the keyword 'Between'.

Update dbo.Claims_Primary_Adjuster_Test_Sujith
SET
Claims_Primary_Adjuster_Test_Sujith.Supervisor = Claims_Internal_Transfer.Supervisor,
Claims_Primary_Adjuster_Test_Sujith.Office = Claims_Internal_Transfer.Office,
Claims_Primary_Adjuster_Test_Sujith.Specialty = Claims_Internal_Transfer.Specialty
from dbo.Claims_Primary_Adjuster_Test_Sujith
Left Outer Join Stg.HS_DW_RV_ClaimsON Claims_Primary_Adjuster_Test_Sujith.Claim_Number = HS_DW_RV_Claims.ClaimNumber

[code]....

how to modify my code such that it works for my condition?

View 10 Replies View Related

T-SQL (SS2K8) :: Merge Statement MULTIPLE INSERT Into Different Tables

Jul 23, 2014

Can we insert into multiple table using merge statement?I'm using SQL Server 2008 R2 and below is my MERGE query...

-> I'm checking if the record exist in Contact table or not. If it exist then I will insert into employee table else I will insert into contact table then employee table.

WITH Cont as
( Select ContactID from Contact where ContactID=@ContactID)
MERGE Employee as NewEmp
Using Cont as con

[code]...

View 2 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

One DELETE Sql Statement To Delete From Two Tables

Aug 12, 2007

I am trying to write one sql statement that deletes from two tables. Is it possible ? If yes, any thoughts ?

View 5 Replies View Related

Why Would Tables Pulled In From ODBC In Access Be Different Than Tables In SQL 2005 Tables?

Jan 24, 2008

I'm new to my company, although not new to SQL 2005 and I found something interesting. I don't have an ERD yet, and so I was asking a co-worker what table some data was in, they told me a table that is NOT in SQL Server 2005's list of tables, views or synonyms.

I thought that was strange, and so I searched over and over again and still I couldn't find it. Then I did a select statement the table that Access thinks exists and SQL Server does not show and to my shock, the select statement pulled in data!

So how did this happen? How can I find the object in SSMS folder listing of tables/views or whatever and what am I overlooking?

Thanks,
Keith

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

DB Engine :: Can't Use The MERGE Statement / How To Design WHERE Condition For Insert Statement

Nov 5, 2015

I've have a need with SQL Server 2005 (so I've no MERGE statement), I have to merge 2 tables, the target table has 10 fields, the first 4 are the clustered index and primary key, the source table has the same fields and index.Since I can't use the MERGE statement (I'm in SQL 2005) I have to make a double step operation, and INSERT and an UPDATE, I can't figure how to design the WHERE condition for the insert statement.

View 2 Replies View Related

SQL Server 2012 :: Update Statement With CASE Statement?

Aug 13, 2014

i was tasked to created an UPDATE statement for 6 tables , i would like to update 4 columns within the 6 tables , they all contains the same column names. the table gets its information from the source table, however the data that is transferd to the 6 tables are sometimes incorrect , i need to write a UPDATE statement that will automatically correct the data. the Update statement should also contact a where clause

the columns are [No] , [Salesperson Code], [Country Code] and [Country Name]

i was thinking of doing

Update [tablename]
SET [No] =
CASE
WHEN [No] ='AF01' THEN 'Country Code' = 'ZA7' AND 'Country Name' = 'South Africa'
ELSE 'Null'
END

What is the best way to script this

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







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