Insert Into ....... Select Clause

Mar 26, 2004

Hi,
I have a question about Insert into .....
Select clause in a SP. I need to insert some rows into a temperary table in a specific order. For example,
insert into #TempTable
{
.......
........
}
Select * from products order by @SortBy @SortDirection.
//
First of all, the order by clause does not take
variables. I have tried to use
declare @query varchar (1000)
set @query = 'Select * from products order by " + @SortBy + ' ' + @SortDirection
exec (@query)
//
However, I get an error message because I should supply a Select statement.
How can I solve this problem??

Thanks for your help!

View 3 Replies


ADVERTISEMENT

Not Able To Do Insert And Select Clause With Aggregate Function

Aug 14, 2006

Hi,

Could some one help me how to do

insert into test2(id,name) values ((select max(id) from test1),'user1')
in MS SQL Server

its throwing "Subqueries are not allowed in this context. Only sc
alar expressions are allowed" Exception. Help is appreciated.

Thanks,
Murali

View 2 Replies View Related

Is It Possible To Re-reference A Column Alias From A Select Clause In Another Column Of The Same Select Clause?

Jul 20, 2005

Example, suppose you have these 2 tables(NOTE: My example is totally different, but I'm simply trying to setupthe a simpler version, so excuse the bad design; not the point here)CarsSold {CarsSoldID int (primary key)MonthID intDealershipID intNumberCarsSold int}Dealership {DealershipID int, (primary key)SalesTax decimal}so you may have many delearships selling cars the same month, and youwanted a report to sum up totals of all dealerships per month.select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',sum(cs.NumberCarsSold) * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDMy question is, is there a way to achieve something like this:select cs.MonthID,sum(cs.NumberCarsSold) as 'TotalCarsSoldInMonth',TotalCarsSoldInMonth * d.SalesTax as 'TotalRevenue'from CarsSold csjoin Dealership d on d.DealershipID = cs.DealershipIDgroup by cs.MonthIDNotice the only difference is the 3rd column in the select. Myparticular query is performing some crazy math and the only way I knowof how to get it to work is to copy and past the logic which isgetting out way out of hand...Thanks,Dave

View 5 Replies View Related

Interaction Between Instead Of Insert Trigger And Output Clause Of Insert Statement

Jan 14, 2008


This problem is being seen on SQL 2005 SP2 + cumulative update 4

I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable

I now need to add an "instead of insert" trigger to the table that is the subject of the insert.

As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows

Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table

Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.

To run the repro below - select each of the sections below in turn and execute them
1) Create the table
2) Create the trigger
3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value
4) Drop the trigger
5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row

I need the behaviour to be correct when the trigger is present

Any thoughts would be much appreciated

aero1


/************************************************
1) - Create the table
************************************************/
CREATE TABLE [dbo].[my_table](
[my_table_id] [bigint] IDENTITY(1,1) NOT NULL,
[forename] [varchar](100) NULL,
[surname] [varchar](50) NULL,
CONSTRAINT [pk_my_table] PRIMARY KEY NONCLUSTERED
(
[my_table_id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 70) ON [PRIMARY]
)

GO
/************************************************
2) - Create the trigger
************************************************/
CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table]
INSTEAD OF INSERT
AS
BEGIN

INSERT INTO my_table
(
forename,
surname)
SELECT
forename,
surname
FROM inserted

END

/************************************************
3) - Do the insert
************************************************/

DECLARE @my_insert TABLE( my_table_id bigint )

declare @forename VARCHAR(100)
declare @surname VARCHAR(50)

set @forename = N'john'
set @surname = N'smith'

INSERT INTO my_table (
forename
, surname
)
OUTPUT inserted.my_table_id INTO @my_insert
VALUES( @forename
, @surname
)

select @@identity -- expect this value in @my_insert table
select * from @my_insert -- OK value without trigger - zero with trigger

/************************************************
4) - Drop the trigger
************************************************/

drop trigger [dbo].[trig_my_table__instead_insert]
go

/************************************************
5) - Re-run insert from 3)
************************************************/
-- @my_insert now contains row expected with identity of inserted row
-- i.e. OK

View 5 Replies View Related

Expression Defined In SELECT Clause Overwrites Column Defined In FROM Clause

May 14, 2008

2 examples:

1) Rows ordered using textual id rather than numeric id


Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
order by
v.id






Result set is ordered as: 1, 11, 2
I expect: 1,2,11


if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

2) SQL server reject query below with next message

Server: Msg 169, Level 15, State 3, Line 16
A column has been specified more than once in the order by list. Columns in the order by list must be unique.




Code Snippet
select
cast(v.id as nvarchar(2)) id
from
(
select 1 id
union select 2 id
union select 11 id
) v
cross join (
select 1 id
union select 2 id
union select 11 id
) u
order by
v.id
,u.id




Again, if renamed or removed alias for "cast(v.id as nvarchar(2))" expression then all works fine.

It reproducible on

Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)


and


Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2)

In both cases database collation is SQL_Latin1_General_CP1251_CS_AS

If I check quieries above on database with SQL_Latin1_General_CP1_CI_AS collation then it works fine again.

Could someone clarify - is it bug or expected behaviour?

View 12 Replies View Related

SELECT Then DELETE Versus Extra Clause In SELECT

Nov 29, 2007

Far below (in section "original 3 steps"), you see the following:1. a temp table is created2. some data is inserted into this table3. some of the inserted data is removed based on a join with the sametable that the original select was made fromIn my opinion, there is no way that the join could produce more rowsthan were originally retrieved from viewD. Hence, we could get rid ofthe DELETE step by simply changing the query to be:INSERT INTO #details ( rec_id, orig_corr, bene_corr )SELECT rec_id, 0, 0FROM viewDWHERE SOURCE_SYS NOT IN ( 'G', 'K' )AND MONTH( VALUE_DATE_A8 ) = MONTH( @date )AND YEAR( VALUE_DATE_A8 ) = YEAR( @date )AND INMESS NOT LIKE '2__' ---- the added line===== original 3 steps (mentioned above) =====CREATE TABLE #details (rec_id UNIQUEIDENTIFIER PRIMARY KEY NOT NULL,orig VARCHAR(35) NULL,bene VARCHAR(35) NULL,orig_corr TINYINT NULL,bene_corr TINYINT NULL)INSERT INTO #details ( rec_id, orig_corr, bene_corr )SELECT rec_id, 0, 0FROM viewDWHERE SOURCE_SYS NOT IN ( 'G', 'K' )AND MONTH( VALUE_DATE_A8 ) = MONTH( @date )AND YEAR( VALUE_DATE_A8 ) = YEAR( @date )DELETE dFROM #details dJOIN viewD v ON ( d.rec_id = v.rec_id )WHERE INMESS LIKE '2__'

View 1 Replies View Related

I Need Help With An Insert Clause, Please Help

Apr 9, 2007

I am trying to write a complex insert statement and not really sure how to get started.First I am building an application to a record label to add artist, songs, pictures, video, and music to their site.Thanks to asp.net 2.0 building the application interface was easy, but now I realize I have run into a brick wall and need some help.in one application, called "add artist album"in this application, you, the website administrator, are adding information to two different tables (artist (holds all info about the artist), album (holds all the info about artist album))I have no clue how to really start writing an insert statement for this.Basically I want to be able to insert the album data (artistid (foreign key), album name and release date) and also have a drop down listbox, which is connected to the database by the sqldatasource connector to allow the administrator to choose an artist from the artist table so that when they add the albem and release date they, the administrator, can choose which artist in the drop down list box to associate with the album and release date data that goes in the album table. That association is made with the artistid because it is a foreign key to the artist table but how do I insert the chosen artistid number into that foreign key field for the album table?
Please can someone point me in the right direction. I am thinking that the insert statement will be something like and insert with nested select statement and inner join included but i haven't a clue how to do this.My table DDLCreate table artist (artistid int prmrykey, artistname varchar (100), bio varchar(100))Create table album (albumid int prmrykey, albumname varchar (100), releasedate date, artistid int foreignkey)My DML for the insert statement so far:ALTER PROCEDURE sp_AddArtistAlbum @AlbumName varchar(50),@ReleasedDate datetime,@ArtistID intAS
SET NOCOUNT ON
DECLARE @AlbumID INT
INSERT INTO tb_Album
(AlbumName, ReleasedDate, ArtistID)
VALUES (@AlbumName, @ReleasedDate, select ArtistID from tb_Artist where ArtistID = (ArtistID from sqldatasource from the drop down listbox) )
Like I said know I am supposed to have a select subquery statement that is nested to really make this thing work but I do not know where to start, can someone please help me. I hope I have provided enough information.My expected results are to insert data from into the album table and have that data associated with an artist chosen in the drop down box.Please Help!!!!!!!!!!!!!!

View 1 Replies View Related

Where Clause In Insert Statement

Jun 27, 2007

Hello all,

I've got a question. I have an array that I am inserting into a table. The code is in classic asp and looks like this:

SQL1 = "INSERT INTO transactionz (classid, userid) values (" & listOfAnswers(i) & ",8)

The problem is that I want to only insert values that have the value "1". listofAnsers is an array that returns values of "1" and "2". If there a way to limit the inserts to values of "1". Another words, I want to just insert the values of "1" into the table. I know that you experts would say I should control this on the code side and thats true, however, I can't (because I don't control the code side) so is there a way to do this via SQL? Am I making any sense? I was thinking that I needed to add a "where" clause at the end of the code, but I don't know where to go from here.

View 1 Replies View Related

WHERE Clause Of An INSERT INTO Statement

Oct 15, 2007



Hi,

I have the following bit of SQL:





Code Block
INSERT INTO [INTRANETSQLEXPRESS].Trapped.dbo.TBL_Debtsolv (Debtsolv_ID, Payment_Amount, Payment_Status, Client_Status)
SELECT Client.ID AS ClientID,
InitialInstallment.OffsetAmountExpected AS FirstExpectedPayment
,
CASE WHEN Payment.TotalPaid <= 0 OR LatestPaymentDate IS NULL
THEN 'No Money Paid'
WHEN Payment.TotalPaid < InitialInstallment.OffsetAmountExpected
AND Payment.TotalPaid >0
AND InitialInstallment.DateExpected + ISNULL(Schedule.DayOffset, 0) >GETDATE()
THEN 'Still Awaiting - Part Paid'
WHEN Payment.TotalPaid >= InitialInstallment.OffsetAmountExpected
THEN '1st Payment Made'
WHEN Payment.TotalPaid < InitialInstallment.OffsetAmountExpected
AND InitialInstallment.DateExpected + ISNULL(Schedule.DayOffset, 0) <GETDATE()
THEN 'Late - First Payment Not Made'
ELSE 'Status Unclear'
END
AS Status
, CASE WHEN
Client.Status IN(0,1,2,3,4,5,6,7)
THEN 'In Preparation'
WHEN Client.Status IN(8,9)
THEN 'Active'
ELSE 'Inactive'
END AS ClientStatus
FROM SALEEN.Debtsolv.dbo.Client_Contact as Client
LEFT OUTER JOIN SALEEN.Debtsolv.dbo.Payment_Schedule AS Schedule
ON Client.ID = Schedule.ClientID
INNER JOIN SALEEN.Debtsolv.dbo.Client_LeadData CLD
ON Client.ID = CLD.Client_ID
INNER JOIN SALEEN.Debtsolv.dbo.Type_Client_Status TCS
ON Client.Status = TCS.ID
LEFT OUTER JOIN SALEEN.Debtsolv.dbo.Type_Lead_Source TLS
ON CLD.SourceID = TLS.ID
LEFT OUTER JOIN SALEEN.Debtsolv.dbo.Type_Lead_Source_Group AS LeadGroup
ON TLS.[Group] = LeadGroup.ID
LEFT OUTER JOIN SALEEN.Debtsolv.dbo.Users [User]
ON CLD.Counsellor = [User].ID
LEFT OUTER JOIN (SELECT ClientID
, SUM(CAST((Amount + ISNULL(AmountOffset, 0))AS Money) / 100) AS OffsetAmountExpected
, MAX(DateExpected) AS DateExpected
FROM SALEEN.Debtsolv.dbo.Payment_Schedule AS PS
WHERE (SequenceID <=(SELECT
CASE WHEN NumInitialInstalments = 0 THEN 1
ELSE IsNull(NumInitialInstalments, 1)
END
AS NumInitialInstalments
FROM SALEEN.Debtsolv.dbo.Client_LeadData AS LD
WHERE (Client_ID = PS.ClientID)))
GROUP BY ClientID
)
AS InitialInstallment
ON Client.ID = InitialInstallment.ClientID
LEFT OUTER JOIN (SELECT Receipt.ClientID
, SUM(CAST(Receipt.Amount AS Money)) / 100 AS TotalPaid
FROM SALEEN.Debtsolv.dbo.Payment_Receipt Receipt
INNER JOIN SALEEN.Debtsolv.dbo.Type_Payment_Status Type
ON Receipt.Status = Type.ID
WHERE (Receipt.Status = 5)
GROUP BY ClientID)
AS Payment
ON Client.ID = Payment.ClientID
LEFT OUTER JOIN (SELECT ClientID
, MAX(ID) AS MaxPSID
, MAX(LastPayment) AS LatestPaymentDate
FROM SALEEN.Debtsolv.dbo.Payment_Schedule Schedule
WHERE (NOT (LastPayment IS NULL)
AND LastPayment > CONVERT(DATETIME, '1980-01-01 00:00:00', 102))
GROUP BY ClientID)
AS LatestPaymentDate
ON Client.ID = LatestPaymentDate.ClientID
INNER JOIN (SELECT ClientID
, MAX(SequenceID) AS LFPDSequenceID
FROM SALEEN.Debtsolv.dbo.Payment_Schedule PS
WHERE (PaymentType = 1)
GROUP BY ClientID)
AS LastPayment
ON Client.ID = LastPayment.ClientID
AND Schedule.ClientID = LastPayment.ClientID
AND Schedule.SequenceID = LastPayment.LFPDSequenceID
WHERE Client.ID = TBL_Debtsolv.Debtsolv_ID




Executing this statement gives the following error:



Code Block

Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "TBL_Debtsolv.Debtsolv_ID" could not be bound.


I think thsi is soemthing to do with referencing another table in the INSERT into command as if I put:




Code Block
WHERE Client.ID = '12065'









The statement executes with no problem. I think I have read in some other threads that you cannot reference another table in the WHERE part of an INSERT INTO clause but cannot find out how I can make this work.

Most of the statement comes from a pre-made report from one of our systems and I have slighlty changed it to insert the data into another database that we have.

Any suggestions would be greatly appreciated

Thanks

View 1 Replies View Related

Select With IN Clause

Aug 3, 2006

Hi SQL Experts,

i have a strange problem

i have a variable which stores some values(ID) with single quote (so that i can use directlt inside the IN Clause of SELECT

Declare @DMSIDs AS VARCHAR(1000) -- variable declare,

Select @DMSIDs = '''DMS00046847'',''DMS00048305''' -- for test putting 2 correct values with escape characters

Select * from issue where id in (@DMSIDs) -- valid statment, but does not return any data
Select * from issue where id in ('DMS00046847','DMS00048305') -- same above constant value this returns data, but putting the values in varaible then trying fails.

The reason is i have a master table called issue and have another table [delta] where a particular column will store all the ID's of the issue table comma separated with single quote and i wanted to use something like below in my actual application

Select * from issue where ID in (Select distinct delta_ID from Delta_branch where date = getdate())
but since the above example with variable is not returning any data i wonder if such is possible in any other ways.

thank you for reading and helping me.

View 3 Replies View Related

Select To Clause

Aug 3, 2007

I'm having trouble using the To clause in my select statement. The following errs out with

Incorrect syntax near the keyword 'to'.


use pubs

select

*

from

view_Rates to 'c: est.csv'

I also tried this and got same error:


use pubs

select

*

to 'c: est.csv'

from

view_Rates

View 6 Replies View Related

How SELECT In WHERE Clause Works?

Jun 8, 2008

Please help 
I'm trying to do a select command but doesn't return any record
I have two tables one is "lists" another one is "list_records"
in the liss table I have 4 records and in the list_records I have only one record which is tell who is already visited the site so I created a query to get people who is NOT visited the site
 
Here is my query (I got 0 record return) 
 
SELECT *FROM lists
list_reccords
WHERE NOT EXISTS (SELECT *
                                                   FROM lists,
                                                      list_records                                       WHERE list_records.is_visited = 1
                                             AND lists.list_id = list_records.list_id)

View 4 Replies View Related

Using Greater Than '&>' In SELECT Clause

Jan 10, 2006

Here is the first part of a query for MySQL that I am trying to get working on MSSQL:


Code:


SELECT n.*,
round((n.rgt-n.lft-1)/2,0) AS childs,
count(*)+(n.lft>1) AS level,
((min(p.rgt)-n.rgt-(n.lft>1))/2) > 0 AS lower,
(( (n.lft-max(p.lft)>1) )) AS upper
FROM table n
...



But, I get this error message:

Server: Msg 170, Level 15, State 1, Line 3
Line 3: Incorrect syntax near '>'.

Is there a way to convert this? Thanks

View 2 Replies View Related

IF Statement In SELECT WHERE Clause

Jun 12, 2008

Hi Everyone,

I have the following stored procedure, I would like to use
IF statement or something of the sort in the where clause i.e.
The last line in the SP is: AND (category.categoryID = @categoryID),
I only want to check this, if @categoryID is not = 12.
So can I do something like this:

IF @categoryID <> 12
AND (category.categoryID = @categoryID)

STORED PROCEDURE:

CREATE PROCEDURE sp_get_total_risk_patients
@categoryID int
AS

SELECT COUNT(DISTINCT patient.patientID) AS total_patients
FROM patient
INNER JOIN patient_record ON patient.patientID = patient_record.patientID
INNER JOIN sub_category ON sub_category.sub_categoryID = patient.sub_categoryID
INNER JOIN category ON category.categoryID = sub_category.categoryID
WHERE risk = 6
AND (completed_date = '' OR completed_date IS NULL)
AND (category.categoryID = @categoryID)

View 4 Replies View Related

Select A As B And Reference B In The Where Clause

Aug 23, 2007

Hello,

When you rename a field/calculation in the select part of the sql statement, how do you reference it in the where clause?

For example:

Select A, B, (C + D) as X
From test
WHERE X > 1

Many thanks!

View 3 Replies View Related

Question About Where Clause In A Select

Feb 28, 2008

Hi,

I have a simple select statement that joins a master and a detail tables using a single field. Looks somthing like this:

Master:
Field1 (Unique key)
more fields...
DateField (Index field)

Detail:
Field1 (unique key)
Field2 (unique key)
more fields....

The master has 100 thousand records and the detail has 100 million records.

If I had a statment "Select.....From Master, Detail" what would be the best way to write the where clause?

Would one of the following where clauses run faster than the other based on the number of records in the tables?

Where1:
where Master.DateField = value and Master.Field1 = Detail.Field1

Where2:
where Master.Field1 = Detail.Field1 and Master.DateField = value

View 3 Replies View Related

CURSOR Select Clause

Oct 11, 2006

I need to dynamically construct the field order of a cursor based on fixed labels from another table, but when I put that resulting query I receive the error:

Server: Msg 16924, Level 16, State 1, Line 78
Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.

I have 6 fields defined in the cursor select, and 6 parameters in the fetch. The results of running the @sql portion returns valid data. Should this be possible to define a parameter containing the select clause of the cursor?

select colnum, coldesc, colname into #ae_defs from ae_adefs
select @Sql = (select colname from #ae_defs where coldesc = 'PATIENT NAME') +
', ' +
(select colname from #ae_defs where coldesc = 'PATIENT NUMBER') +
', ' +
(select colname from #ae_defs where coldesc = 'ACCOUNT NUMBER') +
', ' +
(select colname from #ae_defs where coldesc = 'VISIT DATE') +
', ' +
(select colname from #ae_defs where coldesc = 'VISIT TYPE') +
', DocID from ae_dtl1'

DECLARE myCursor CURSOR FOR
Select @SQL

OPEN myCursor
print @@Cursor_rows
FETCH NEXT FROM myCursor into @var1, @var2, @var3, @var4, @var5, @DocID

View 2 Replies View Related

SQL Server 2012 :: OVER Clause With Insert Very Slow

Sep 29, 2015

I am using an aggregate with the OVER clause.Running the script is fast less than 1 second but when I say insert into a temp table the execution plan is very different at it take 8 seconds.I have attached the execution plans. Also the Statistics IO, Time messages. I am using SQL Server 2014 with backward compatibility to 2008 R2.

if (select OBJECT_ID('tempdb..#MM')) is not null drop table #MM
CREATE TABLE #MM ([MyTableID] [int], [ParticipantID] [int], [ConferenceID] [nvarchar](50), [Points] [money], [DateCreated] [datetime], [StartPoints] [money], [EndPoints] [money], [LowPoints] [money], [HighPoints] [money])
insert into #MM ([MyTableID], [ParticipantID], [ConferenceID], [Points], [DateCreated], [StartPoints], [EndPoints], [LowPoints], [HighPoints])
selectmm.MyTableID, mm.ParticipantID, mm.ConferenceID, mm.Points, mm.DateCreated,

[code]....

View 2 Replies View Related

'SELECT Clause Does Not Return Rowset From Sp'

May 3, 2004

I have sp20, simplified, as:

ALTER PROCEDURE dbo.sp20 (@CustomerID int, @aDate as datetime) AS

SELECT Customers.* INTO #EndResult1 FROM Customers WHERE Customers.CustomerID >= @CustomerID

SELECT Orders.* INTO #EndResult2 FROM Orders Where Orders.[TakenDate] >= @aDate

SELECT #EndResult1.*, #EndResult2.*
FROM #EndResult1 INNER JOIN #EndResult2 ON #EndResult1.CustomerID = #EndResult2.CustomerID

This works fine in EM.

When I try to execute it from MS Access ADP Project I get

'Stored Procedure excuted succesfully, but did not return any records'

Although, in EM it returns the right number of records.

Thank you in advance - Rehman

View 2 Replies View Related

UDefined Functions In Select/ Where Clause

Sep 11, 2000

Hi,

Is there any way of emulating Oracle's capability of passing output of user-defined functions in the select statement or better still in the Where clause in SQL server 7.0? If not then could we hope for it in SQl server 2000?

Regards,
Vikas..

View 1 Replies View Related

Use A Variable Along With The FROM Clause In SELECT Statement

Dec 28, 2004

I have a table 'table_list' which contains two columns, table_name and a record_count. This table stores a list of tables and their corresponding record counts.

What I am trying to do is, to be able to write a select statement, that can read each table name in the 'table_name' column, execute a select count(*) for the same, and update its record_count with the result of select count(*).

This is the code in my procedure..

DECLARE @tab_list CURSOR
set @tab_list = CURSOR FOR select * from table_list
OPEN @tab_list

DECLARE @tab_name varchar(256)
DECLARE @rec_cnt int
FETCH NEXT FROM @tab_list INTO @tab_name, @rec_cnt

select count(*) from @tab_name

This select is looping around along with FETCH till all the table names are exhausted and their counts are updated from the cursor back into the table.

Problem is that, I am not able to use select count(*) from @tab_name, and its not accepting a variable there.

Please help me to construct the select statement that is similiar to

x=<table name>
select * from x
where x is a variable and the table name gets substituted.

what is the syntax for it ?

View 7 Replies View Related

Grouping Select Statements With Where Clause

Aug 10, 2004

Hello

What I need to do is be able to group the results of my select statements in different columns. And end having the result work like this.


campaign Col1 Col2

<<Data>> <<Select counT(*) where field= value>> <<Select counT(*) where field= value>>

View 1 Replies View Related

Optimising Select Statements Which Has A ‘LIKE’ Where Clause.

Dec 14, 2004

Hi all

I have been doing some development work in a large VB6 application. I have updated the search capabilities of the application to allow the user to search on partial addresses as the existing search routine only allowed you to search on the whole line of the address.

Simple change to the stored procedure (this is just an example not the real stored proc):

From:
Select Top 3000 * from TL_ClientAddresses with(nolock) Where strPostCode = ‘W1 ABC’
To:
Select Top 3000 * from TL_ClientAddresses with(nolock) Where strPostCode LIKE ‘W1%’

Now this is when things went a bit crazy. I know the implications of using ‘with(nolock)’. But seeing the code is only using the ID field to get the required row, and the database is a live database with hundreds of users at any one time (some updating), I think a dirty read is ok in this routine, as I don’t want SQL to create a shared lock.

Anyway my problem is this. After the change, the search now created a Shared Lock which sometimes locks out some of the live users updating the system. The Select is also extremely SLOW. It took about 5 minutes to search just over a million records (locking the database during the search, and giving my manager good reason to shout abuse at me). So I checked the indexes. I had an index set on:

strAddressLine1, strAddressLine2, strAddressLine3, strAddressLine4, strPostCode.

So I created an index just for the strPostCode (non clustered).

This had no change to the ‘Like select’ what so ever. So I am now stuck.

1)Is there another way to search for part of a text field in SQL.
2)Does ‘Like’ comparison use the index in any way? If so how do I set this index up?
3)Can I stop a ‘Shared Lock’ being created when I do a ‘like select’?
4)Do you have any good comebacks I could tell the boss after his next outburst of abuse (please not so bad that he sacks me).

Any advice truly appreciated.

View 8 Replies View Related

How To Select Last Rows In Group By Clause

Nov 7, 2008

I have a table which stores datewise Transactions of different items. Fields and sample data is

RecID, ItemID, Date, Received, Issued, Stock
1, 5, 11-03-08, 10, 10
2, 5, 11-05-08, 3, 7*
3, 8, 11-15-08, 25, 25
4, 8, 11-16-08, 8, 33
5, 8, 11-18-08, 6, 27*

Now i want to select last row for each item (indicated by *). Is it possible in one single statement.

View 6 Replies View Related

How To Reference Embedded Select In WHERE Clause

Oct 22, 2013

I need to check the value of a column being pulled from an embedded select in the WHERE clause of a script but can't figure out how to do it. The script looks like this:

SELECT
LIST_ID,
NAME,
ADDRESS
(SELECT ANSWER FROM VALID_ANSWER WHERE VALID_ANSWER.LIST_ID = VIEW_LIST.LIST_ID) AS ANSWER

FROM VIEW_LIST

WHERE ANSWER = 'No'

The syntax above works in Oracle but in SQL Server I receive the following error: "Invalid column name 'OHIP'."

View 6 Replies View Related

Select Distinct Results From Where Clause?

Jul 14, 2014

Just wondering if it's possible to select distinct results from the where clause?

View 3 Replies View Related

Select .. NOT IN Clause Doesn't Return Anything?

Nov 3, 2005

Hi there,

It's a very strange thing!
I havea a table called invoices, and a table calle customer payments which has the invoiceID of the payment.

I have many invoices that haven't been paid (so they don't have a record on the customer payments). I know this, as i can for example do:
select * from invoices where invoiceID = 302247 (and i'll get one result)
select * from customer_payments where invoice = 302247 (and i'll get none results)

however, if i do the following:
select * from invoices where invoice_id not in
(select invoice_id from customer_payments)
I get nothing!!!???

It doesn't make any sense, as I should get at least 300 (including the 302247) - both invoiceids fields are int... so i just don't understand what's wrong?

thank you so much for any help!



Grazi

View 6 Replies View Related

Use Of User Defined In SELECT Clause

Jul 23, 2005

I'm having this query:SELECTss.subscription_id AS SubscriptionId,s.id AS ScopeId,s.[name] AS ScopeName,s.base AS ScopeBase,dbo.iqGetShapesByScopeAsString(s.id) AS ShapesAsStringFROMsubscription_scope ss,scope sWHEREss.subscription_id = @subscription_idANDss.scope_id = s.idORDER BYs.[name]The select only returns a single row but my database (SQL Server 2005CTP) seems to execute the "iqGetShapesByScopeAsString" function foreach row in the subscription_scope and scope tables. This is a bug,right? The function should be executed only once for each *returned*row in the SELECT, right? I believe that was the case in SQL 2k thoughI can't check it at the moment.// pt

View 6 Replies View Related

Select Inner Join With Where Clause Problems

Jan 3, 2007

Hello All,

I have a question about a Select over 2 Tables,
with the Following Scenario (Not all Products (ARTICULOS) haves CARAC's on the CFG_CARAC_ARTICULOS table):

Picture of the tables here:
http://www.pci-baleares.com/pantallazoSql.jpg



We have per example 7 Slots (Motherboard, CPU, VGA Card, RAM, TOWER, etc...)
When we fill the Slot with a CPU-> Then we open the Slot for VGA CARD, we do the Followin Select:

SELECT dbo.ARTICULOS.*
FROM dbo.CFG_CARAC_ARTICULOS INNER JOIN
dbo.ARTICULOS ON dbo.CFG_CARAC_ARTICULOS.ID_ARTICULO = dbo.ARTICULOS.ID_ARTICULO

Ok it brings up ALL Graphic Cards because they dont depends on CPU

Now we go to the Motherboard Slot
And we make the following Select to obtain the compatible Motherboards:
SELECT dbo.ARTICULOS.*

FROM dbo.CFG_CARAC_ARTICULOS INNER JOIN

dbo.ARTICULOS ON dbo.CFG_CARAC_ARTICULOS.ID_ARTICULO = dbo.ARTICULOS.ID_ARTICULO

WHERE

((dbo.CFG_CARAC_ARTICULOS.ID_CARAC = 7) AND (dbo.CFG_CARAC_ARTICULOS.VALOR = 'PCI-E')) AND
((ID_CARAC = 1) AND (VALOR = '775'))

We check the motherboards if they support PCI-E (because we selected a Graphic card of that, and SOCKET 775 because the CPU)

But SQL return 0 Rows, if we do the following Select:
SELECT dbo.ARTICULOS.*


FROM dbo.CFG_CARAC_ARTICULOS INNER JOIN


dbo.ARTICULOS ON dbo.CFG_CARAC_ARTICULOS.ID_ARTICULO = dbo.ARTICULOS.ID_ARTICULO


WHERE


((dbo.CFG_CARAC_ARTICULOS.ID_CARAC = 7) AND (dbo.CFG_CARAC_ARTICULOS.VALOR = 'PCI-E'))

OR

SELECT dbo.ARTICULOS.*


FROM dbo.CFG_CARAC_ARTICULOS INNER JOIN


dbo.ARTICULOS ON dbo.CFG_CARAC_ARTICULOS.ID_ARTICULO = dbo.ARTICULOS.ID_ARTICULO


WHERE

((ID_CARAC = 1) AND (VALOR = '775'))

It return Rows, it happens just if the Where clause haves more as 1 specifications...

Any solution for it? It drives me crazy :D

Thanks and regards
Marc Hägele

View 3 Replies View Related

Is It Possible To Use A Where Clause In Select Statments When You Use Intersection?

Apr 26, 2008


Lets say that Dealers have ZipCodes, and that a Dealer can have more than one zipCode, and we want the list of dealers that have both 90210 and 90211 zip codes. BUT we don't want any dealers that have only one of the two ZipCodes in question

What I want to do is something like this

Select DealerID from DealerZips where Zip = '90210'
intersection
Select DealerID from DealerZips where Zip = '90211'

but I get this error msg:
Line 2: Incorrect syntax near 'intersection'




The following sql is silly, but it does run without error
Select DealerID from DealerZips
intersection
Select DealerID from DealerZips

So I am pretty sure my problem is with the Where clauses.

help!

View 3 Replies View Related

Select Stored Procedure With One Parameter And A Where Clause

Jan 13, 2007

Here is my procedure:
ALTER PROCEDURE dbo.SelectMeds
@RX int
AS
SELECT RX FROM tblMeds WHERE RX= @RX
 
RETURN
but it return no rows, how do I fix this?

View 4 Replies View Related

How Do I Select Data Using A Datetime Field In The Where Clause?

Oct 15, 1998

I would like to do something like this, but it does not work.

Select * from PS_AUDIT_EMPLYMNT
WHERE AUDIT_STAMP LIKE `Oct 15 1998%`

*Note AUDIT_STAMP is a Datetime field

Does anyone have any ideas why this will not work?

Thanks,

Rodney

View 3 Replies View Related

Does The Group By Have To Include All Fields From The SELECT Clause?

Dec 3, 2007

hey all,

say i have the following function

SELECT GLF_CHART_ACCT.DESCR1, F1ADR_ADDRESS.ADDR1, F1ADR_ADDRESS.ADDR2,
F1ADR_ADDRESS.ADDR3, F1ADR_ADDRESS.ADDR_CITY, F1ADR_ADDRESS.ADDR_STATE,
F1ADR_ADDRESS.POST_CODE, F1ADR_ADDRESS.PHONE_NBR, F1ADR_ADDRESS.FAX_NBR,
F1ADR_ADDRESS.EMAIL_ADDR_NAME, F1ADR_ADDRESS.CONTACT_NAME,
F1ADR_ADDRESS.CONTACT_TITLE, GLF_CHART_ACCT.ACCNBRI, F1ADR_ADDRESS.ENTITY_UNIQUE_NBR

FROM GLF_CHART_ACCT

INNER JOIN F1ADR_ADDRESS ON (GLF_CHART_ACCT.CHART_NAME = F1ADR_ADDRESS.ENTITY_KEY1)
AND (GLF_CHART_ACCT.ACCNBRI = F1ADR_ADDRESS.ENTITY_KEY2)

GROUP BY GLF_CHART_ACCT.DESCR1, F1ADR_ADDRESS.ADDR1, F1ADR_ADDRESS.ADDR2,
F1ADR_ADDRESS.ADDR3, F1ADR_ADDRESS.ADDR_CITY, F1ADR_ADDRESS.ADDR_STATE,
F1ADR_ADDRESS.POST_CODE, F1ADR_ADDRESS.PHONE_NBR, F1ADR_ADDRESS.FAX_NBR,
F1ADR_ADDRESS.EMAIL_ADDR_NAME, F1ADR_ADDRESS.CONTACT_NAME, GLF_CHART_ACCT.ACCNBRI,
F1ADR_ADDRESS.CONTACT_TITLE, GLF_CHART_ACCT.CHART_NAME, F1ADR_ADDRESS.ENTITY_UNIQUE_NBR,
GLF_CHART_ACCT.SELN_TYPE1_CODE

HAVING CHART_NAME='ARCHART' AND GLF_CHART_ACCT.DESCR1 <> '' AND GLF_CHART_ACCT.SELN_TYPE1_CODE = 'Trade'
AND GLF_CHART_ACCT.DESCR1 LIKE '%" + Search + "%' ORDER BY GLF_CHART_ACCT.DESCR1;

I get errors if not all the fields are included in the group by clause.

what i dont get is why i have to create seperate groups for this query...or am i reading it wrong??

Cheers,

Justin

View 5 Replies View Related







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