Inserting Conditions In A Select Statement

Jun 12, 2007

How can i insert a if-else condition in a select statement or is there a way to specify a condition within a select statement?
Any reply is really appreciated..thank you..

shemay

View 11 Replies


ADVERTISEMENT

Using IF ElSE Like Conditions In An Select Statement

Mar 17, 2006

Hi All,
This is my problem. I need the out put of a sql select statement to be "true" or "false" depending on the actual columns value is positive or negative. Does any one how to do this.
Thanks in advance,
-VJ

View 1 Replies View Related

Inserting Conditions In Stored Procedures

Jun 12, 2007

How to insert if-else statements to my stored procedure if i am only going to set a condition on a single column of the table?

Ex. SELECT a.m0020_pat_id, a.M0040_PAT_LNAME + ', ' + a.M0040_PAT_FNAME + ' ' + a.M0040_PAT_MI as patientName,
a.M0030_START_CARE_DT as socdate, M0906_DC_TRAN_DTH_DT as transferdate,M0906_DC_TRAN_DTH_DT+14 as DueDate, M0230_PRIMARY_DIAG_ICD, c.[description] AS M0230_PRIMARY_DIAG_DESC,
d.name facilityName, e.FacilityTypeName,a.EffectiveDate_End

( i will specify that if MO906_DC_TRAN_DTH+14 is greater than EffectiveDate_End THEN MO906_DC_TRAN_DTH+14=EffectiveDate_end)


shemay

View 1 Replies View Related

Multiple Conditions In IF Statement In T-SQL?

Jul 20, 2005

Hi All,Just wondering if anyone can tell me if you can test for multipleconditions as part of an "IF" statement in T-SQL in SQL Server 2000?ie something like:IF @merr = 1 or @merr=2BeginSELECT statementUPDATE statementEndAny help much appreciated!Much warmth,M.

View 1 Replies View Related

Reporting Services :: Multiple Conditions In IIF Statement?

Jul 8, 2015

I have a table with the following fields and data:

Offense, Year, Month, Count, Amount
F 2007 January 11 $49,238.00
F 2007 February 12 $24,000.00
F 2007 March 31 $55,184.00
F 2007 April 19 $64,647.00
F 2007 May 33 $100,010.00
F 2007 June 16 $59,678.00
F 2007 July 22 $39,700.00
F 2007 August 3 $9,000.00
F 2007 September 4 $75,000.00
F 2007 October 8 $19,250.00
F 2007 November 50 $106,153.00
F 2007 December 26 $80,000.00

I have data for years 2007-2014. I am designing an SSRS report, and want to use IIF statement to return data. Using the following:

=IIF(Fields!Year.Value="2007" AND Fields!Month.Value="February", "return value of count field", "n/a")

The above does not work, it doesn't return the value of Count field, it does return the n/a.

View 14 Replies View Related

Select Max Value From Prior Where Conditions

Apr 7, 2006

I can't figure this out for the life of me. Wanted to know if it's possible to select certain date conditions in a query, then later reference those conditions and to only select the max of them.

I need to do this dynamically as I do not know what the max value is. I've provided an example below:

Select var1
From table1
where
(
(Date1 = '11/30/2005')
OR
(Date1 = '12/31/2005')
)
and Date1 = (Max of previously selected values e.g. '12/31/2005')

What I can't figure out is how to dynamically retrieve the max of 11/31/2005 and 12/31/2005. Any ideas are greatly appreciated.

View 1 Replies View Related

Select With Multiple Conditions

May 12, 2008

Select c.Plan, c.ClaimNumber
from tbFLags c inner join tbMembers m
On c.Claim = m.HistoryNum
where c.Plan = 'J318' and c.Paymon = c.Rmon and c.Rmon = '2008-03-01'


Now I want to add these into this statement, what should be done.



Members meeting any of the 3 sets of criteria should not be selected

1) tbFlags.Hosp='1'

2) tbFlags.RD='1' OR tbCMSFlags.RAType in ('D', 'I2')

3) Deceased = tbMembers.DOD is not null.

View 27 Replies View Related

1. Select A Field Twice With Different (special) Conditions

Sep 12, 2007

Hi guys,

My challenge is really 3 problems in 1.

I have Table1 and Table2 which are inner joined with an ID.
Each record in Table1 may have up to two corresponding values in Table2, which are Type and Name.

req1- I want to select Table2.Name twice (or more), with each selection conditioned on a specific Type.
req2- I also want all information pertaining to the same ID to be returned in each row
req3- I want all IDs to be returned, even if Table2.Name are empty for Type1 and/or Type2.

So, the source tables look something like this:

Table1.ID | ……
-----------------------
ID001
ID002
ID003
ID004

Table2.ID | Table2.Type | Table2.Name
--------------------------------------------------------
ID001 | Type1 | NameA
ID001 | Type2 | NameB
ID002 | Type1 | NameC
ID003 | Type2 | NameD


Ideally, my results should look like this:

Table1.ID | Table2.Name (Type=1) | Table2.Name (Type=2)
----------------------------------------------------------
ID1 | NameA for Type1 | NameB for Type2
ID2 | NameC for Type1 | (empty)
ID3 | (empty) | NameD for Type2
ID4 | (empty) | (empty)

Right now, I can only get Table2.Name to display once, and it won’t return the empty values, even with outer joins. The structure that I’m using is:

SELECT …
FROM …
WHERE Table2.Name IN
(SELECT Table2.Name
FROM Table1 INNER JOIN Table2 …
WHERE Table2.Name = ‘Type1’)

Sorry the abstractness, but this is the simplest way for me to express the problem.

Any help will be appreciated, thanks!

View 4 Replies View Related

Transact SQL :: Select Seems To Be Ignoring WHERE Conditions

Apr 23, 2015

SQL Version:  2008 (not r2)
Problem:  My Select statement seems to be unaffected by some of the conditions in the WHERE Clause.  For instance

JCCD.Mth >= cutoffs.FiscalYear_FirstMonth (value '20130101') AND JCCD.Mth <= @WIPMonthCurrent (value '20130101')AND LTRIM(RTRIM(JCCD.Job)) = '71-' (see output and code below)
SQL Code:
declare @WIPMonthCurrent date  = '20130101'
SELECT  
     JCCD.JCCo, JCCD.Job, JCCD.Mth, JCCD.Source, sum(JCCD.ActualCost) AS CostToDate

[code]....

View 5 Replies View Related

T-SQL (SS2K8) :: Select Query With Multiple Where Conditions And OR Operator

Feb 6, 2015

I have the got below T SQL query to fetch the matching record

DECLARE @MappingTable TABLE
(
Productname nvarchar(10),
identification_key1 int,
identification_key2 int,
identification_key3 int

[Code] .....

-- result - 'Orange'

This is an exact matching record and straight forward

Is it possible to identify the record using T SQL query based on the following scenarios

1) return the record - If all the three where conditions match
2) if record not found check and return the record where 2 columns values in the where condition match

-- Expected Result for below query: 'Orange', because 2 of the columns in where condition have matching values

SELECT Productname
FROM @MappingTable where identification_key1=1 or identification_key2 =2 or identification_key3 =1

-- result - 'Orange'

View 4 Replies View Related

SQL Server 2008 :: Join Another Table But With Select Conditions?

Mar 24, 2015

I have this sql....

Select
DISTINCT p.dbPatID, p.dbpatfirstname, p.dbPatLastName,
s.dbSchTypeCnt as SchDetailType, t.dbSchTypeCnt as SchTypeType,
ISNULL(r.dbStatusDesc, 'No Ref') AS dbStatusDesc,
ISNULL(t.dbSchTypeCode, 'No Ref') AS dbSchTypeCode,
ISNULL(t.dbSchTypeDesc, 'No Ref') AS dbSchTypeDesc,

[code]....

however, I only want the lastest a.dbPatApptTime and only when a.dbPFStatus = 1 and a.ClientRef = 'EPS'

So the stand alone sql could be....

Select Top(1) dbPatApptTime as LastVisitDate, dbSchTypeDesc as LastVisitDesc
from appointments
where dbPFStatus = 1 and clientref = 'EPS'
order by dbPatApptTime desc

I'm just not sure how to incorporate that into my sql or whether there is a better way,

View 9 Replies View Related

Select Rows Based On Multiple Date Conditions

Jun 5, 2008

Hi,
I have 1 table with 5 rows. One of the rows has dateTime values. I want to know how many rows there are with a value in that column < today AND how many rows there are with a value in that column > today.
I'm not sure how to do this.

SELECT Count(*) WHERE dateColumn <= today AND dateColumn > today gives me everything.
I like to end up with a column containing the count of rows <= today
and a column with rows where date > today.

Is this possible in SQL or do I have to retrieve all rows and then loop over the resultset and check each row?

Thanks,
Marc

View 2 Replies View Related

JOIN Efficiency Using Multiple ON Conditions Versus WHERE Conditions

Jan 10, 2008

My question is fairly simple. When I join between two tables, I always use the ON syntax. For example:


SELECT

*
FROM

Users

JOIN UserRoles

ON (Users.UserRoleId = UserRoles.UserRoleId)


No problems there. However, if I then decide to further filter the selection based on some trait of the UserRole, I have two options: I can add the condition as a WHERE statement, or I can add the condition within the ON block.

--Version 1:

SELECT

*
FROM

Users

JOIN UserRoles

ON (Users.UserRoleId = UserRoles.UserRoleId)
WHERE

UserRoles.Active = 'TRUE'


-- Version 2

SELECT

*
FROM

Users

JOIN UserRoles

ON (Users.UserRoleId = UserRoles.UserRoleId

AND UserRoles.Active = 'TRUE')


So, the question is, which is faster/better, if either? The Query Analyzer shows the two queries have the exact same execution plan, which makes sense, since they're both joining the same tables. However, I'm wondering if adding the condition in the ON statement results in fewer rows the JOIN statement initially needs to join up, thus reducing the overall initial size of the results table before the WHERE conditions are applied.

So is there a difference, performance wise? I imagine that if Users had a thousand records, and UserRoles had 10 records, then the JOIN would create a cartesian product of the two tables, resulting in 10,000 records in the table before the WHERE conditions are applied. However, if only three of the UserRoles is set to Active, would that mean that the resulting table, before applying WHERE conditions, would only contain 3000 records?

Thanks for whatever information you can provide.

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

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

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

SQL Statement For Inserting Date && Auto-increment Fields

Dec 8, 2006

I have a (1) date field and (2) an auto-incrementing ID field that always throw me errors when I'm doing a programmatic insert.
 
(1) After doing many searches on the subject, I don't think I'm using the correct syntax for the date and can't find any suggestion that works. Would appreciate your knowledge on correct SQL syntax for inserting a "today's date" field.
 
(2) I'm using the following code to create a new auto-incrementing ID for each record but it seems that there should be a smoother method to force the field's value to auto-increment. Any ideas?
 
Private objCmd As SqlCommand Private strConn As New SqlConnection(ConfigurationManager.AppSettings("conn"))...objCmd = New SqlCommand("select max(ClientID) from tblClients", strConn)Dim intClientID As Int16 = objCmd.ExecuteNonQuery + 1

View 5 Replies View Related

Inserting Data - Maximum Characters Exceeded In Statement

Nov 29, 2014

I am new to SQL but have managed to create a table with five columns. The problem I am having is when I try and run the INSERT command I get an error "Maximum characters exceeded in SQL statement"

My table code is:

create table myemployees_MPA0510
(FirstName Varchar (15), LastName
varchar (20), Title varchar (25),
Age number (3), salary number (9));

And my INSERT code is:

Insert into myemployees_MPA0510
(First, Last, Title, Age, Salary)
Values ('Jonie', 'Weber', 'Secretary', 28, 19500.00) ('Potsy', 'Webber', 'Programmer', 32,
45300.00) ('Dirk', 'Smith', 'Programmer II', 45 75020.00) ('Mark', 'Aldridge' 'Technical', 52,
12000.00) ('Peter', 'Wright' 'Admin' 30, 11000.00) ('Lucy', 'May', 'Technical', 15500.00)
('Robert', 'Hurst', 'Finance', 54, 16000.00) ('Ann', 'Green', 'HR', 43, 21000.00);

View 2 Replies View Related

SQL Server 2012 :: Inserting Dummy Records Using Loop Statement

Jul 17, 2015

I have the following attributes in this Table A.

1) Location_ID (int)
2) Serial_Number (nvarchar(Max))
3) KeyID (nvarchar(max)
4) Reference_Address (nvarchar(max)
5) SourceTime (datetime)
6) SourceValue (nvarchar)

I am trying to create 1000000 dummy records in this this table A.How do i go about do it? I would like my data to be something like this

LOCATION_ID
1

Serial Number
SN-01

KeyID
E1210

Reference_Address
83

SourceTime
2015-05-21 00:00:00 000

SourceValue
6200

View 7 Replies View Related

Inserting Rows Into A Temp Table Created By An Execute Statement

Dec 16, 2007

Below is a simplified table & dataset to illustrate a problem I'm experiencing with a more complex one.





Code Block

create table #test(
recno smallint PRIMARY KEY,
value decimal (18,2))

insert into #test values (1, 3.57)
insert into #test values (2, 5.32)
insert into #test values (3,6.29)
insert into #test values (4, 9.25)
insert into #test values (5, 0.84)

Method 1: I tried inserting rows from #test into a temp table (#table) as follows




Code Block

declare @n as nvarchar(3)
set @n = 1
while @n <= (select count(recno) from #test)
begin
exec ('
insert into ##table
select *,
originalrecno = (select recno from #test where recno = '+@n+')
from #test'
)
set @n = @n + 1
end
However, this yields an error message:




Code Block

Server: Msg 208, Level 16, State 1, Line 2
Invalid object name '##table'.
Note - you can comment out the insert into ##table line above to view the results that I'm trying to put into ##table.


Method 2: next I tried explicitly creating ##table & rerunning the loop containing the insert




Code Block

create table ##table (
recno smallint,
value decimal (18,2),
originalrecno smallint)

declare @n as nvarchar(3)
set @n = 1
while @n <= (select count(recno) from #test)
begin
exec ('
insert into ##table
select *,
originalrecno = (select recno from #test where recno = '+@n+')
from #test'
)
set @n = @n + 1
end
This worked - it inserted the data from the select statements in the loop into ##table.

Question - why won't method 1 work?

View 6 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 And Then Inserting Results Into Two Different Tables

Dec 2, 2003

Hello!
I've got the following procedure:
ALTER PROCEDURE [GetTimeDiff2] (@ID int) AS
select
A_ProspectPipeline.ID,
(case when [Completion Date] is null
then '13'
else
case when YEAR([Completion Date])>year(GETDATE())
then '13'
else
case when YEAR([Completion Date])<year(GETDATE())
then '1'
else month([Completion Date])
end
end
end)-
(case when YEAR([Start Date])=year(GETDATE())
then month([Start Date])
else
case when YEAR([Start Date])<year(GETDATE())
then '1'
else '13'
end
end)as [CY],

(case when [Completion Date] is null
then '13'
else
case when YEAR([Completion Date])>year(GETDATE())+1
then '13'
else
case when YEAR([Completion Date])<year(GETDATE())+1
then '1'
else month([Completion Date])
end
end
end)-
(case when YEAR([Start Date])=year(GETDATE())+1
then month([Start Date])
else
case when YEAR([Start Date])<year(GETDATE())+1
then '1'
else '13'
end
end)as [NY]

from a_ProspectPipeline where A_ProspectPipeline.ID = @ID

What i need to do is insert the two returned values [NY] + [CY] into two different tables.
Can anyone help me with this?

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

Inserting From A Distinctly Easy Select...*snicker*

Dec 20, 2005

Hi all...I have taken a look at an archive search, and continue to research and play with mysel...errr...my select, but in the meantime...what am I missing?!?!?!

Here is my excruciatingly interesting insert statementINSERT INTO dbo.WON_MutualFundNames
SELECT UPPER(FndTickerSym), FndName
FROM L_WONDA_MUTUALS.wondb.dbo.funds
WHERE FndTickerSym LIKE '[A-Z]%[X]' /* first char is A thru Z and last char is X*/
GROUP BY FndTickerSym, FndName

Everything works just hunky-dory, EXCEPT for...two @#$(*#& rows in my database table:
FndTickerSym FndName
------------- -------------------------------
DHMBX DREYFUS YIELD MUNICIPAL BOND
dhmbx DREYFUS YIELD MUNICIPAL BOND

What has befuddled me is that when I run the SELECT by itself, only ONE of the rows is returned - - only when I combine it with the insert, I get a duplicate primary key value error (the FndTickerSym is the insert-table's primary key column).

WTF is goin' on, dudes? And perhaps more importantly, how can I get around it?

Any suggestions are welcome

well...any except "delete the duplicate row", which I am already crafting an email about to send to the offending/offensive (I assure you, they are both) group that maintains the data in this table. However, whenever I make my database idiotproof, they always invent a craftier idiot...so I must code the insert to work if such a situation presents itself again in the future.

Thoughts? Suggestions? New Cursewords?

View 2 Replies View Related

Inserting A Select With An Additional Static Field

Jul 20, 2005

I have a stored procedure where I want to select all fields matchingthe query into another table. In addition, I want to add a commongroupID to each of the records that are being inserted into the secondtable.I can get the results that I want by using a temporary table but needto know if there is a way to do it directly..below is the code that uses the temporary table..CREATE TABLE #tempStore_DeliveryAddress ([AddressId] [int] IDENTITY (1, 1) NOT NULL ,[UserId] [int] NOT NULL ,[Title] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[FirstName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[SpouseName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[MiddleName] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[SpouseMiddleName] [varchar] (10) COLLATESQL_Latin1_General_CP1_CI_AS NOT NULL ,[LastName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[SpouseLastName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_ASNOT NULL ,[Suffix] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[SpouseSuffix] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Company] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Address1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Address2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Address3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[City] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[State] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[PostalCode] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[Country] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[ForeignFlag] [int] NULL CONSTRAINT[DF_Store_DeliveryAddress_ForeignFlag] DEFAULT (0),[Email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,[Greeting] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[FullName] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[ShortName] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOTNULL ,[OptOut] [int] NULL CONSTRAINT [DF_Store_DeliveryAddress_OptOut]DEFAULT (0),[Modified] [datetime] NULL CONSTRAINT[DF_Store_DeliveryAddress_Modified] DEFAULT (getdate()),[Modifer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_Store_DeliveryAddress_Modifer] DEFAULT ('DBA'),[Created] [datetime] NULL CONSTRAINT[DF_Store_DeliveryAddress_Created] DEFAULT (getdate()),[Creator] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_Store_DeliveryAddress_Creator] DEFAULT ('DBA'),[MailListID] [int] NULL ,CONSTRAINT [PK_Store_DeliveryAddress] PRIMARY KEY CLUSTERED([AddressId]) ON [PRIMARY]) ON [PRIMARY]INSERT INTO #tempStore_DeliveryAddress([UserId], [Title], [FirstName],[SpouseName], [MiddleName], [SpouseMiddleName], [LastName],[SpouseLastName], [Suffix], [SpouseSuffix], [Company], [Address1],[Address2], [Address3], [City], [State], [PostalCode], [Country],[ForeignFlag], [Email], [Greeting], [FullName], [ShortName], [OptOut],[Modified], [Modifer], [Created], [Creator])(SELECT [UserId], [Title], [FirstName], [SpouseName], [MiddleName],[SpouseMiddleName], [LastName], [SpouseLastName], [Suffix],[SpouseSuffix], [Company], [Address1], [Address2], [Address3], [City],[State], [PostalCode], [Country], [ForeignFlag], [Email], [Greeting],[FullName], [ShortName], [OptOut], [Modified], [Modifer], [Created],[Creator]FROM [ntmportal].[dbo].[Store_AddressBook]WHERE [AddressID] in (Select AddressID From Store_AddressesForGroupwhere AddressGroupID = 322))UPDATE #tempStore_DeliveryAddress set MailLISTID = 422INSERT INTO Store_DeliveryAddress([UserId], [Title], [FirstName],[SpouseName], [MiddleName], [SpouseMiddleName], [LastName],[SpouseLastName], [Suffix], [SpouseSuffix], [Company], [Address1],[Address2], [Address3], [City], [State], [PostalCode], [Country],[ForeignFlag], [Email], [Greeting], [FullName], [ShortName], [OptOut],[Modified], [Modifer], [Created], [Creator], [MailListID])(Select [UserId], [Title], [FirstName], [SpouseName], [MiddleName],[SpouseMiddleName], [LastName], [SpouseLastName], [Suffix],[SpouseSuffix], [Company], [Address1], [Address2], [Address3], [City],[State], [PostalCode], [Country], [ForeignFlag], [Email], [Greeting],[FullName], [ShortName], [OptOut], [Modified], [Modifer], [Created],[Creator], [MailListID]FROM #tempStore_DeliveryAddress)

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

Out Of Range Datetime Value Error When Inserting Using Select...union

Mar 7, 2006

Hi all,I am getting this error when insert values from one table to another inthe first table the values are varchar (10). In the second they aredatetime. The format of the data is mm/dd/yyyy to be easily convertedto dates. The conversion in this case is implicit as indicated in SQLServer documentation. Here is my query:INSERT INTO Campaign (CampaignID, Name, DateStart, DateEnd, ParentID,ListID)SELECT mysqlfactiva.dbo.campaigns.campaign_id AS CampaignID,mysqlfactiva.dbo.campaigns.campaign_name AS Name,MIN(mysqlfactiva.dbo.programs.start_date) AS DateStart,MIN(mysqlfactiva.dbo.programs.end_date) AS DateEnd,NULL AS ParentID,NULL AS ListIDFROM mysqlfactiva.dbo.campaigns, mysqlfactiva.dbo.programsWHERE mysqlfactiva.dbo.campaigns.campaign_id =mysqlfactiva.dbo.programs.campaign_idGROUP BY mysqlfactiva.dbo.campaigns.campaign_id,mysqlfactiva.dbo.campaigns.campaign_name,mysqlfactiva.dbo.campaigns.descriptionUNIONSELECT program_id + 100000, program_name, start_date, end_date,campaign_id AS ParentID, NULL AS ListIDFROM mysqlfactiva.dbo.programsUNIONSELECT execution_id + 200000, execution_name, start_date,end_date, program_id + 100000 AS ParentID, NULL AS ListIDFROM mysqlfactiva.dbo.executionsUNIONSELECT wave_id + 300000, wave_name, start_date, end_date,mysqlfactiva.dbo.waves.execution_id + 200000 AS ParentID, NULL ASListIDFROM mysqlfactiva.dbo.waves, mysqlfactiva.dbo.executionsWHERE mysqlfactiva.dbo.waves.execution_id =mysqlfactiva.dbo.executions.execution_idI am referencing programs table two times. If I just select this all Iget all data I need. When doing insert I get a message:Server: Msg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted inan out-of-range datetime value. The statement has been terminated.If I execute just first part of the query before first union, I insertdata fine:INSERT INTO Campaign (CampaignID, Name, DateStart, DateEnd, ParentID,ListID)SELECT mysqlfactiva.dbo.campaigns.campaign_id AS CampaignID,mysqlfactiva.dbo.campaigns.campaign_name AS Name,MIN(mysqlfactiva.dbo.programs.start_date) AS DateStart,MIN(mysqlfactiva.dbo.programs.end_date) AS DateEnd,NULL AS ParentID,NULL AS ListIDFROM mysqlfactiva.dbo.campaigns, mysqlfactiva.dbo.programsWHERE mysqlfactiva.dbo.campaigns.campaign_id =mysqlfactiva.dbo.programs.campaign_idGROUP BY mysqlfactiva.dbo.campaigns.campaign_id,mysqlfactiva.dbo.campaigns.campaign_name,mysqlfactiva.dbo.campaigns.descriptionAs soon as I use union I get the above error. This is very strangesince even when I execute the query using first union where the datescome from the same table 'programs' I get the error. Why I can insertfrom programs first time and can's second time?Any help will be appreciated.Thanks,Stan

View 1 Replies View Related







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