Selecting From Different Tables
Jul 23, 2005
Using SQL2000. How do I format my select statement to choose one out
of 24 different tables? Each table is slightly different and I was
hoping I could use one select statement and format it on-the-fly
instead of using 24 different ones. I had in mind using a case
statement, something like this:
select * from
case when <input parameter> = 'something1' then tblSomething1
case when <input parameter> = 'something2' then tblSomething2
...and so on...
Thanks for any help.
View 4 Replies
ADVERTISEMENT
Nov 1, 2006
Hello I have two tables:
Package
PakageID Destination Source
1 xyz abc
And
PendingPackages
ClientID PackageID Status
1 1 0
How would I create a select statement to select all rows from Package (PackageID, Destination, Source) where the CleintID=1 and the PackageID exists in pending packages with a status of 0?
Can this be done using a select statement or would I have to create a view? I'm not too sure!
Thanks :)
View 3 Replies
View Related
Feb 12, 2006
Plugging away at my little message board that I am working on, I have hit another SQL snag. I am trying to select a list of all posts in a thread. I have to get each post, the name of the poster (which comes from a different table - referenced by userid), as well as some profil information, from a 3rd table (also referenced by the userid).
View 2 Replies
View Related
Jul 30, 2001
Hi all,
I have a query similar to this:
select "bcp databasename.."+name+"
from sysobjects where type = 'U'
order by name
What I need to know is that, I need to unselect some of the tables that starts with name cj_. I don't want the tables that starts with a name cj_.
Can someone help me on this.
Thank you
View 3 Replies
View Related
Apr 2, 2007
Hi all.
I'm trying to select from multiple table in one select statement but i'm having problems. Here is the code i'm trying:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[snow_ors_additionalInfoRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[snow_ors_additionalInfoRead]
GO
CREATE PROCEDURE dbo.snow_ors_additionalInfoRead
@Reference int
AS
SELECT
Account.CanTravel,
Account.SEEmployee,
Account.WorkHours,
Account.DrivingLicence,
Account.CriminalConvictions,
Account.CriminalConvictionsDetails1,
Account.CriminalConvictionsDate1,
Account.CriminalConvictionsDetails2,
Account.CriminalConvictionsDate2,
Account.CriminalConvictionsDetails3,
Account.CriminalConvictionsDate3,
Application.VacancyMonitoring,
Application.VacancyMonitoringDetails
FROM Account, Application
WHERE Account.Reference = @Reference AND
Application.reference = @Reference
GO
Any help at all would be great.
thanks people.
View 5 Replies
View Related
Aug 13, 2006
Hi there,I'm new to sql and thus I'm having problems with a specific query which Ihope you guys can help me with.Basicly I have a few tables which I'm trying to do a query on:Table groups contains information about specific groups e.g. "Windows" or"Unix".Table users contains information about specific users e.g. "a", "b" or "c".Table users_groups contain information about group relationship (a user canbe in multiple groups) e.g. (a, Windows), (b, Unix), (a, Unix).In this case user c is ungrouped.Now I'd like to find the users which does belong to group Windows and thosewho do not:select distinct username from users_groups where groupname = "Windows" orderby username asc;This works pretty well for finding users in the specific group. In this casethe result is a.However I'd like to get the opposite result (b and c) but I'm stuck.The problem is that I'd like a list of all users excluding those which arein "Windows"Here is a partial query:select distinct users.username from users left join users_groups onusers.username = users_groups.username where users_groups.username is nullorder by users.username asc;This only gives me those users who are not grouped at all. This mean thatuser b is not in those results.Please advise.Thanks in advance.-- Henrik
View 2 Replies
View Related
Aug 5, 2004
Hi there,
I have the following script that selects tables from my database with the same column name and then I delete data that falls within a specified condition. However what I need to be able to do is just select these tables that meet the condition and then just delete the data because at the moment it's also returning tables that I don't need.
So I just want to use a cursor on a table list that meet the criteria:
1) have qid column name
2) qid >= 5000000 and qid < 1500000000 '
Example
declare @strqry varchar(1000)
declare dailyYear cursor
for SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE 'qid' = COLUMN_NAME order by table_name asc
open dailyYear
fetch next from dailyYear into @DelTable
while @@FETCH_STATUS = 0
begin
Set @strqry = 'Delete from '+@DelTable+' where qid >= 5000000 and qid < 1500000000 '
exec(@strqry)
fetch next from dailyYear into @DelTable
end
close dailyYear
deallocate dailyYear
Any help would be greatly appreciated!!
Thanks
S
View 3 Replies
View Related
Sep 2, 2004
Hi there,
Is there a quick way to select all the tables in the DB that don't have certain column in the table, so for example getting a list of all tables that don't have columns: A, B or C?
Thanks
S
View 4 Replies
View Related
Feb 19, 2004
Hello,
Is it possible to get a list of rows from Multiple tables which have the same Column Name. I have 3 tables which comtain similar info
and I want to get a list of Names
the structure is
ID;Name;Address;Phone No.
I was thinking something along the lines of SELECT Name FROM TABLE1,TABLE2, TABLE3
But this does not work.
Is there a nice way of doing this with SQL or should I do code outside the SQL DB
View 4 Replies
View Related
Apr 18, 2008
Hi
Is there a way to select out the contents of sys.comments for an object (in this case, a procedure) so that it is nicely formatted?
The reason being, is that I want to update source control with all objects from the live environment (as it has become out of date.... long story). Currently, we have a single script for each object, split in directories for each object type. Anyway, I also want to wrap the objects in our standards (check for object existence, print out success/fail statements, etc).
Any suggestions to make the process more automated and less painfull? I don't want to have to script each object out, manually wrap it in standards and save as that would be perhaps the most tedious task in the world!!!!
Thanks!
Hearty head pats
View 2 Replies
View Related
Aug 27, 2007
Hello Tsql experts,
Can you please explain to me what the differnce is between selecting into a table and creating a new tabel and inerting in to it like so:
First way:
select names
into #ancestors
from names
and
second way
create table #names(
name varchar(10)
)
insert into #names (name) values(name)
select names from names
is it just personal choice or performance in one method is better than the other.Can you please explain.
Thanks
View 3 Replies
View Related
Oct 6, 2006
Hello!I have two tables:Pressreleases:| Pressrelease_ID | PressDate | FilePath | Title |PressLinks:| PressLink_ID | PressLinkDate | PressLinkUrl | PressText |I would like to select the the TOP 3 with the most recent dates from either Pressreleases or PressLinks, and present them in a DataList. How do I do that? Selecting from one table is no problem:SELECT TOP 3 Pressreleases.PressDate, Pressreleases.Filepath, PressReleases.Title FROM Pressreleases ORDER BY PressDate DESCHow do I select from both tables and rename the columns to Date, Path, Text so that I can use it in a Datalist?Thank you in advance!
View 4 Replies
View Related
Jan 5, 2008
I want to select columns from different tables into a single table...Not sure if a temp table is suited for this and if so how I should implement it (NOTE: this query will be executed many times by different users at the same time, so I'd rather avoid temp tables!)I have:TABLE1idfirstnamedescriptioncreatedateTABLE2idcarnamespecificationsimportdateNow, I want a resultset that has the columns (columns from other tables from which the values should be retreived are behind the desired columns):id (TABLE1.id, TABLE2.id)title (TABLE1.firstname , TABLE2.carname)description (TABLE1.description , TABLE2.sepcifications)date (TABLE1.createdate , TABLE2.importdate)Thanks!
View 1 Replies
View Related
Feb 10, 2002
This is feeling very hard for me, but is surely very easy for many of you.
I have 2 Tables. "Events" and "Meals". Both have a columns named "EventDate" and "EventTime". I need to be able to compile a list of both and sort by event date and time. For example, a Meal @ 5:30 would place itself between a 4:00 Event, and a 6:30 Event.
PLEASE HELP ME!!!
Pending deadline doom :(
Thanks,
kaskenasy@publishingconcepts.com
View 1 Replies
View Related
Jun 4, 2014
I have 3 tables:
News:
bigint NewId
nvarchar NewTitle
datetime NewDate
nvarchar NewBrief
--------------------------
Category:
int CatId
nvarchar CatName
--------------------------
NewsRelCategory:
bigint Id
int CategoryIdFk
bigint NewsIdFk
--------------------------
I want to select NewId, NewDate and Distinct NewTitle
I tried this but NewTitle doesn't distinct:
SELECT
FROM dbo.Category INNER JOIN
NewsRelCategory ON dbo.Category.CatId = NewsRelCategory.NrcCategoryIdFk INNER JOIN
dbo.News ON NewsRelCategory.NrcNewsIdFk = dbo.News.NewId
View 9 Replies
View Related
Sep 6, 2006
Hi
I currently have two tables called Book and JournalPaper, both of which have a column called Publisher. Currently the data in the Publisher column is the Publisher name that is entered straight into either table and has been duplicated in many cases. To tidy this up I have created a new table called Publisher where each entry will have a unique ID.
I now want to remove the Publisher columns from Book and JournalPaper, replace it with an ID foreign key column and move the Publisher name data into the Publisher table. Is there a way I can do this without duplicating the data as some publishers appear several times on both tables?
Any help with this will be greatly appreciated as my limited SQL is not up to this particular challenge!!!
Thanks!
View 7 Replies
View Related
Dec 15, 2006
I moved this from another forum because it seems more related to replication the longer I look into it!
The following code often dies on a deadlock. I have also seen "Spid x blocked by Spid x", where x is the spid of this connection. The view selects from several tables and some other views as well, and many of the underlying tables are being updated by replication. I have seen cases where the replication Insert proc participated in the deadlock, and the table being inserted into is joined twice in the view, suggesting that somehow this
causes the deadlock or makes a deadlock more likely?
SELECT * INTO dbo.tbl_stg_LoansMarketingFirstBorrower
FROM view_loans_marketing_first_borrower OPTION (MAXDOP 1)
I do not understand how selecting from a view can cause a deadlock with a
proc which does not reference tbl_stg_LoansMarketingFirstBorrower. Any
suggestions on how to diagnose this? I used (1204) to identify the proc and underlying table.
Thanks a bunch.
View 1 Replies
View Related
Mar 17, 2008
hello guys,
I have 10 tables, table1, table2, table3, table4.......table10. all these tables have different structure.
From each of these tables I want extract data and dump into flat file csv.
So i have OLEDB source and FlatFile Destination.
If i write seperate data flow task for each of the tables, then there is no issue.
But i want to use a single data flow task for all these tables. So for this, i use a variable @SQLStr . And i dynamically set the value of this variable to select * from table1, select * from table2.........selct * from table10.
So in the OLEDB source I select Data Access Mode as : SQL Command from variable. And I use @SQLStr for this varible.
For Destination, i dynamically generate the flat file for each of the table.
But this doesnt work, i get validation errors.
So, first can i use a single data flow task to dynamically change the source(different source tables) and destination. If so, what i am missing in the above process?
any help appriciated.
Thanks
View 8 Replies
View Related
Oct 6, 2006
I am pulling info out of MSDB to report on job schedules. As we have a mixture of 2005 and 2000 servers, I am varying my select statement according to the result of
[Code]
Set @Version = SubString(Convert(VarChar(10), (Select ServerProperty('ProductVersion'))),1,1)
[/Code]
I have to vary the tables for each condition. Not a problem,
[Code]
if @Version = 9
begin
Select whatever from table1 join table2
end
Else
begin
Select whatever from table1 join table3
end
Problem is that SQL 2005 is trying to verify the existence of the fields in the tables on compile (it knows that the table, for example, sysjobschedules exists in 2005, but the field "Name" doesn't - although it does in 2000) , even after the if statement checking if the version is 8, and SQL 2000 uses 2 tables whilst 2005 needs 3, and the fields I need are on one table in 2000, but in a different table in 2005.
SQL 2000 is fine with it - it just does it.
Syntax checking is fine.
Just to clarify, here is my code:
[Code]
Declare @Version Char(1), @CurrentDate datetime
Set @CurrentDate = GetDate()
Create Table #TempSchedDetails
( Server VarChar(30)
,CurrentDate VarChar(19)
,JobName VarChar(80)
,ScheduleName VarChar(80)
,Freq_Type Char(1)
,Freq_Interval VarChar(2)
,JobEnabled Bit
,Freq_Subday_Type VarChar(25)
,ScheduleEnabled Bit
,StartTime VarChar(25)
,EndTime VarChar(25)
)
Set @Version = SubString(Convert(VarChar(10), (Select ServerProperty('ProductVersion'))),1,1)
If @Version = '9'
Begin
Insert Into #TempSchedDetails
Select left(@@SERVERNAME,30)
,GetDate()--@CurrentDate
,J.Name
,SS.Name
,SS.Freq_Type
,SS.Freq_Interval
,J.Enabled
,SS.Freq_SubDay_Type
,SS.Enabled
,SS.Active_Start_Time
,SS.Active_End_Time
From msdb..SysJobs J
Left Outer Join msdb..SysJobSchedules JS on J.Job_Id = JS.Job_Id
Join msdb.dbo.SysSchedules SS ON JS.schedule_id = SS.Schedule_Id
Order By J.Name, Active_Start_Time
End
Else
Begin
Insert Into #TempSchedDetails
Select left(@@SERVERNAME,30)
,@CurrentDate
,J.Name
,S.Name
,S.Freq_Type
,S.Freq_Interval
,J.Enabled
,S.Freq_SubDay_Type
,S.Enabled
,S.Active_Start_Time
,S.Active_End_Time
From MSDB..SysJobs J
Left Outer Join MSDB..SysJobSchedules S On J.Job_Id = S.Job_Id
Order by J.name, Active_Start_Time
End
[/Code]
Any ideas as to how to turn the precompile checking off in 2005?
View 3 Replies
View Related
Nov 30, 2007
Hi,
I was wanting to know if it is possible to create a left join when selecting from 3 seperate tables.
Select p.Project_name, p.project_id, cp.email_display_name, te.Mon
FROM tblProject p, tblCorpPerson cp, tblTimeEntry te
WHERE p.Project_ID = te.Project_ID
AND p.Person_ID = @PersonID
AND cp.Person_ID = p.Person_ID
I need to return all rows from tblProject, and any matching project_id's from tblTimeEntry.
Any ideas or suggestions?
Thanks
View 24 Replies
View Related
Sep 19, 2000
I want to have a linking table say for example we call this a claim. Based on the claim number you need to relate to one of say 6 different types of claims. The types of claims related to their own individual parent table. (individual because each type of claim tracks completely different information) does anyone have an idea on how to set this up?
Sample Structure
table = Claim
Field 1 = ClaimTypeA_ID
Field 2 = ClaimTypeB_ID
Field 3 = ClaimTypeC_ID
Field 4 = ClaimTypeD_ID
Field 5 = ClaimTypeE_ID
Field 6 = ClaimTypeF_ID
The six field relate to the 6 different tables ID.
If I do this how do I store the data? put 0's in each of the claim types that are not used???
Any suggestions would be appreciated.
View 2 Replies
View Related
Jul 1, 2015
i have this query in a proc
declare @bu_id INT,
@CurCaptureDate DATETIME,
@user_id INT,
@col_name VARCHAR(100),
@sort_order VARCHAR(4),
@CityPair_ID INT=NULL,
[code]....
where @reasons and @departure_code can be multiple.
View 2 Replies
View Related
Dec 8, 2007
Hi,
First the environment: two tables A and B.
Table A: ID (unique-identifier)
Table B: ID_A (unique-identifier to A.ID, relation)
DTime (datetime)
Rows (id1 and id2 are Id examples):
A: id1
id2
B: id1 and 12:00:00 (date not important)
id1 and 13:00:00
id2 and 12:00:00
Example:
SELECT A.ID, B.DTIME
FROM A
LEFT JOIN B ON B.ID_A = A.ID
WHERE B.DTime < '14:00:00'
ORDER BY NEWID()
When I run this, I get the three rows of table B. But what I want is to get each table A row once, and get the nearest datetime of WHERE expression from the relation of table B.
So, the result must been two rows, id1 and id2, and id1 with '13:00:00' row because this is the nearest value of '14:00:00'.
How can I do this? DISTINCT trying by A.ID of SELECT, but doesn't work. Also ORDER BY B.DTime will work, but not random by NEWID() anymore.
Thank you.
View 3 Replies
View Related
Mar 23, 2008
Im just curious how i would take multiple columns from multiple tables.... would it be something like this ???
table: Products COLUMNS ProductName, ProductID
table: Categorys COLUMNS CategoryName, CategoryID,ProductID
SELECT Products.ProductName, Categorys.CategoryName,Products.ProductID,Categorys.CategoryID,Categorys.ProductID
FROM Categorys, Tables
WHERE Products.ProductID = Categorys.ProductID
View 1 Replies
View Related
May 4, 2007
I'm using a Business Intelligence project to copy stored procedures and tables from one database to another across servers. I'm having trouble copying tables or stored procedures using the Management.SMO.Transfer class.
I tried copying stored procedure with the property transfer.CopyAllStoredProcedures = true. This didn't work. As a workaround, I used the StringCollection property and executed every string as sql.
Now I'm having trouble copying tables. I don't want to copy all the tables in the database. How do I go about selecting what tables to copy. I tried using ObjectList property and provided the names of the tables in an ArrayList. I get the error
"Transfer cannot process System.String. You need to pass an instance class object."
How can I pass an "instance class object" for something that's in the database? The ScriptTransfer method fails so I can't even see the script that is being generated. There is virtually no documentation for this class.
Any help will be appreciated.
Transfer transfer = new Transfer();
transfer.Database = sourceDB;
transfer.DestinationDatabase = DestinationDatabase;
transfer.DestinationServer = DestinationServer;
transfer.DropDestinationObjectsFirst = false;
transfer.CopyData = true;
transfer.CopySchema = true;
transfer.CopyAllObjects = false;
transfer.CopyAllTables = false;
transfer.CopyAllStoredProcedures = false;
transfer.Options.WithDependencies = false;
GetTablesToBeCopied();
transfer.ObjectList = tablesList;
transfer.Options.FileName = "C:\TransferScriptTables.sql";
StringCollection coll = transfer.ScriptTransfer();
View 3 Replies
View Related
Sep 20, 2007
I've got a big problem that I'm trying to figure out:
I have an address table out-of-which I am trying to select mailing addresses for companies UNLESS a mailing address doesn't exist; then I want to select the physical addresses for that company. If I get multiple mailing or physical addresses returned I only want the most recently edited out of those.
I don't need this for an individual ID select, I need it applied to every record from the table.
My address table has some columns that look like:
[AddressID] [int]
[LocationID] [int]
[Type] [nvarchar](10)
[Address] [varchar](50)
[City] [varchar](50)
[State] [char](2)
[Zip] [varchar](5)
[AddDate] [datetime]
[EditDate] [datetime]
AddressID is a primary-key non-null column to the address table and the LocationID is a foreign key value from a seperate Companies table.
So there will be multiple addresses to one LocationID, but each address will have it's own AddressID.
How can I do this efficiently with perfomance in mind???
Thank you in advance for any and all replies...
View 2 Replies
View Related
Nov 4, 2004
i want to select all the user tables within the database and then all the records with in each table.
plz tell me one query to do this.
ex: suppose x and y are user tables and x contain 10 records and y contains 20 records . i want a query which displays all 30 records together.
View 1 Replies
View Related
Feb 21, 2006
A colleague of mine has a view that returns approx 100000 rows in about 60 seconds.
He wants to use the data returned from that view in an OLE DB Source component.
When he selects the view from the drop-down list of available tables then SSIS seems to hang without any data being returned (he waited for about 15 mins).
He then changed the OLE DB Source component to use a SQL statement and the SQL statement was: SELECT * FROM <viewname>
In this instance all the data was returned in approx 60 seconds (as expected).
This makes no sense. One would think that selecting a view from the drop-down and doing a SELECT *... from that view would be exactly the same. Evidently that isn't the case.
Can anyone explain why?
Thanks
-Jamie
View 2 Replies
View Related
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
Jun 10, 2004
Hi,
I am trying to select all entries from a database apart from the top/latest entry, via a stored procedure.
Below is the code that i have but i am doing it wrong somehow.
Any ideas?
Thanks
CREATE PROCEDURE spNEWSARCHIVE AS
SELECT *
FROM tblNEWS
WHERE NewsID NOT TOP 1
ORDER BY NewsID DESC
GO
View 7 Replies
View Related
Apr 14, 2006
Hi,I have the following set and would like to select all rows that havemin value of column 4 for a given column 1 and 2 group, irrespective ofcolumn 3, as below:C1 C2 C3 C4---------------------A B x 5A B y 10A BB XX 55A BB YY 11AA CC z 1AA CC zz 11Need---A B x 5A BB YY 11AA CC z 1using sql server 2000 (which does not provide rank or partition by)Thanks in advance,Tamas
View 2 Replies
View Related
Sep 5, 2006
Hello,I have a gridview bound to a sqldatasource control. I have an emptydatatemplate setup. In the selecting event, I make sure that an actual select has been performed (and not on null data); however, I have cancelselectonnullparameters set to true to stop it, because initially it will be null.However, the selecting event runs, even when I cancel it, the emptydatatemplate shows up. How do I prevent that from occuring?
View 2 Replies
View Related
Jan 7, 2007
Hi Folks,
You can select all fields with:SELECT * FROM [TableName]
How do you select NOTHING or NONE with a SELECT statement?
Thanks
View 4 Replies
View Related