How To Select Table Info?

Apr 7, 2008

Hi

Can someone write a query for me that would return names of tables that would slelect all tables of particular database and show if table has set primary key and if it has then if key has Identity Specification set to true?

something like:

SELECT
TABLE_NAME
,HAS_PRIMARY_KEY
,KEY_HAS_IDENTITY_SPECIFICATION
FROM
...this is where you come in
ORDER BY
TABLE_NAME

View 6 Replies


ADVERTISEMENT

How To Select Table Info?

Apr 7, 2008

Hi

Can someone write a query for me that would return names of tables that would slelect all tables of particular database and show if table has set primary key and if it has then if key has Identity Specification set to true?

something like:

SELECT

TABLE_NAME
,HAS_PRIMARY_KEY
,KEY_HAS_IDENTITY_SPECIFICATION
FROM

...this is where you come in
ORDER BY

TABLE_NAME

View 3 Replies View Related

SQL Server 2005 Reporting Svcs - How To Use Dataset 1 Info To Drive Nested Table Select

May 20, 2008

I've only been doing sql 2005 for a couple of months with minimal training so there's a lot I don't know.
What I'm trying to do is load a nested table (industry & customer totals) based on a value from the table it's nested in.
This is the relationship of the data.
I have at the highest group, an industry code, then a customer, then the part and then the fiscal year.
What I'm trying to accomplish is to get a group total (footer) for the (1) industry code and (2) the customer code. This footer would contain the fiscal years (ascending) and their monthly totals. I would like to take the industry code from table one and pass it to the select statement in the dataset that feeds the nested table. I've read this is not possible to load a dataset field into a parm but I've seen where some people know how to work around this. If you reply, please explain in simple terms. Thanks!


industry Customer Year OCT NOV DEC
001 - Signposts
M12345
Part 1
2006 5 6 2
2007 0 3 1


Part 2
2006 4 3 0
2007 1 0 7

Customer M12345 totals
2006 9 9 2
2007 1 3 8


M45678
Part 3
2007 8 4 7
2008 3 4 8


Part 4
2006 3 8 7
2007 5 6 6


Customer M45678 totals
2006 3 8 7
2007 13 10 13
2008 3 4 8
Industry 001 totals




2006 12 17 9
2007 14 13 21
2008 3 4 8

View 1 Replies View Related

Is There A System Table With Timestamp Info Or DTS Job Info?

May 7, 2007

I want to be able to see when records have been added to a table. The issue is we have a DTS job scheduled to run every night. The developer who wrote it password protected it and doesn't work here anymore. I want to add a step to this series of DTS jobs and want to run it just prior to his job. Is there a way to see when the records are being added or when this job is being run? Thanks again, you guys are the best.

ddave

View 3 Replies View Related

Select Specific Info From XML Field?

Nov 10, 2014

I have a table (InfoTable) with a field with XML info like this:

<Status>
<IdStatus>1<IdStatus>
<NomStatus>Status 1<NomStatus>
<IdStatus>2<IdStatus>
<NomStatus>Status 2<NomStatus>

]Code] ...

I want to be able to select then NomProcess where IdProcess=3, for instance.

How can I do it?

View 1 Replies View Related

How To Get Info In SELECT Directly Instead Of UPDATE? Thanks.

Jul 23, 2005

Greetings!I have the 3 raw data tables below, and would like to extract somedata. My current query is really cumbersome, does anyone know a betterway to get all the info (attach the right state to the lowest zip code)in one step? Thanks a lot! Here are the details.- Ideal Output, for each person , keep(1) person_id (From Table A)(2) The earliest open_date of accounts starting with 2 (From Table A)(3) ssn (From Table B)(4) Zip and state info (From Table C), but only keep the lowest zip andstate.-Table A -person_idaccountopen_date10001220000015/15/200310001220000026/20/200410001300000012/2/200210002220000038/12/200410002220000049/15/200410002300000022/16/2005-Table B -person_idzip state1000111111AA1000122222CC1000233333BB--Table C -person_idssn100011234567100022345678-Ideal Output-person_idmin_openssnzipstate100015/15/2003123456711111AA100028/12/2004234567833333BBHere is what I did:Select a.person_id, min(a.open_date), b.ssn, min(c.zip) as zip,cast (0 as varchar) as stateInto output[color=blue]>From TableA as a[/color]Join TableB as bon a.person_id=b.person_idJoin TableC as con a.person_id=c.person_idWhere a.account like '2%'Group by a.person_id, b.ssnOrder by a.person_idUpdate outputSet output.state=b.state[color=blue]>From output as a[/color]Join TableC as bon a.person_id=b.person_idand a.zip=b.zip

View 2 Replies View Related

Trying To Select Info With If Exists Statement With No Avail

Jan 6, 2004

Im trying to select rows on the following criteria

My app has a user that can have x jobs, each job has related entries which are marked has unread or read. I need to return any jobs that contain any unread entries also I need to return other jobs that have no entries marked as read.

I am able to return the following:


Comment UnReadMy Job 164
Comment UnReadFor Cam 166

Comment ReadThe Job 157
Comment ReadThird 159
Comment ReadMy Job 164
On Site Visit ReadMy newest job for log test 167

but as you can see jobid 164 appears in both groups and I need it to be one or the other

I tried using the if exists statement and was only able to return one group either unread or read, not both. I've tried everything but I'm new and I figure that theres got to be a more elegant way. Heres my sql:


CREATE PROCEDURE spGetJobsByUnreadAndReadByUserID
@UserID INT
AS


BEGIN
IF EXISTS(SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'UnRead')


BEGIN
SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'UnRead'

ORDER BY BackUp_Read ASC
END

ELSE

BEGIN


SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'Read'

ORDER BY BackUp_Read ASC
END
END
GO


Thanks again

View 12 Replies View Related

Delete Rows In One Table By Referencing Another Table Info

Sep 16, 2004

I have one table that has unique id's associated with each row of information. I want to delete rows of information in one table that have a unique ID that references information in another table.

Here is a basic breakdown of what I am trying to do:

Table1 (the table where the rows need to be deleted from)
Column_x (Holds the id that is unique to the various rows of data - User ID)

Table2 (Holds the user information & has the associated ID)
Column_z (holds the User ID)

I tried this on a test set of tables and could not get it to work. What I am trying to do is skip all rows of Table1 that have ID's present in Table2, and delete the rows of ID's that are not present in Table2.

Code:


SELECT Column_z
FROM dbo.Table2
DELETE FROM dbo.Table1
WHERE Column_z <> Column_x


This did not seem to do what I needed, it did not delete any rows at all.

I wanted it to delete all rows in Table1 that did not have a reference to a user ID that matched any ID's in Column_z of Table2

Then I tried another scenerio that I also needed to do:

Code:


SELECT Column_z, Column_a
FROM dbo.Table2
DELETE FROM dbo.Table1
WHERE Column_z = Column_x AND Column_a='0'



'0' being the user id is inactive so I wanted to delete rows in Table1 and remove all references to users that were in an inactive status in Table2.

Neither one of the Queries wanted to work for me in the Query Analyzer when I ran them. It just said (0) rows affected.

Any ideas on what I am doing wrong here?

View 3 Replies View Related

Not Sure How To Get Info From Other Table

Aug 31, 2005

I am having problems with my store procedure displaying my last column name which is "DISPLAY_CATEGORY_DESC". I am trying to display the description from another table. But in order to get to the description I have to go through 2 tables. The tables look like something like this.

First TableTABLE_CATEGORY

PRIMARY_KEY = DIR_CATEGORY_ID = 5000

Column Name
DIR_CATEGORY_LVL_ID1 = 100
DIR_CATEGORY_LVL_ID2 = 200
DIR_CATEGORY_LVL_ID3 = 300

Second TableTABLE_CATEGORY_DESCRIPTION
PRIMARY KEY DIR_CATEGORY_LVL_ID1 = 100

Column Name
DESCRIPTION = "Car Model Company"

This is my DISPLAY_CATEGORY_DESC

Not sure how to get to this description. Thanks for your help.


select cwebs.SESSION_ID, webs.ENTERED_DATE, cwebs.DIR_CATEGORY_ID, DISPLAY_CATEGORY_DESC

FROM di_webclickstats cwebs
left join di_websessions webs on cwebs.session_id = webs.session_id
where cwebs.DIR_CATEGORY_ID <> 0 and webs.ENTERED_DATE between @startDate and @endDate+1

View 3 Replies View Related

Table Usage Info

Jan 14, 2002

Is there a utility or function or 3rd party product that will show information about tables and other objects such as:

Last change date
Last used date
Where Used
more .....

I'm from an AS/400 environment and found it VERY useful to be able to access that kind of information to clean-up, monitor & manage the systems.

Any Ideas ?

View 1 Replies View Related

Same Table - Subset Of Info

Oct 25, 2007

I'm beating my head up against a wall here. I have one very LARGE table called op_hist.

CREATE TABLE [dbo].[op_hist] (
[op_trnbr] [int] NOT NULL ,
[op_type] [varchar] (80) ,
[op_date] [smalldatetime] NULL ,
[op_act_setup] [decimal](38, 10) NULL ,
[op_act_run] [decimal](38, 10) NULL ,
[op_qty_comp] [decimal](38, 10) NULL ,
[op_wkctr] [varchar] (80) ,
[op_part] [varchar] (30)

)

I need to be able to sum items grouped by op_wkctr and op_part and op_date. Here's my latest version which of course does not work.

SELECT op_wkctr, pcs, hrs.b
FROM
dbo.op_hist
INNER JOIN
(
SELECT op_part, SUM(op_qty_comp) as pcs
FROM dbo.op_hist
where op_type='BACKFLSH'
group by op_hist.op_part

UNION ALL

SELECT op_part, SUM(op_act_setup + op_act_run) as b
FROM dbo.op_hist
where op_type='LABOR'
group by op_hist.op_part
) AS hrs
ON op_hist.op_part = hrs.op_part
where (op_wkctr = 'P-P36' or op_wkctr = 'P-P38' or op_wkctr='P39') and op_date ='10/22/07'

Help me oby one - you're my only hope.

Sincerely,
Frustrated!

View 4 Replies View Related

Move Info From A Table In One Db To Another

Mar 25, 2008

Hello All.

I just made some huge changes to a database on the development computer. However, I want to transfer all of the information from the Employees table in the old DB to the new DB (no changes made on that table).

Can anyone point me in the right direction?

View 4 Replies View Related

How Would You... (binary Info In A Table)

Sep 15, 2007

I have run into a challenge that I'm not sure how to best solve. I'dappreciate any opinions or input.I am working with a third party database. They are storing some datathat I need to use in a binary field. I've got the code to parse thebinary and reconstruct what I need. Unfortunately, there might bemultiple "entries" stored in a single binary field. a certain byte,let's just say the first, will always be the count of "entries" inthis particular SQL entry.An example:then entry might be:0x01000012341234where 12341234 is the data entry that I will parse.Another possible entry is:0x03000012341234567856789ABC9ABCThe first byte indicates that there are three data values I want toparse out:12341234567856789ABC9ABCThe portions of the binary I need are always the same length and theremay be from 1 to ~100 of them. (usually 1 if it matters.)The big question:How could a SQL query return an entry for each of the "entries" in thebinary field? For the second example I would want three entries in myresults, each row returning a different section of the binary data.For the first, only one row. I'll be querying the set and expecting toget back more results than the number of entries in the set.I haven't really tried much with this yet, (other than some mentalcalisthenics were I fell down onto the mat pretty hard), so just somedirection on where to begin would be helpful.(Yes, I understand that the difficulty is that this data shouldn't bestored this way, but there is not much I can do about that.)Thanks...James FraserJoin Bytes!

View 4 Replies View Related

How To Get Table Info From RID Deadlock ?

May 7, 2007

Hi There



I am trying to troubleshoot deadlock issues.

The dead lock is with a RID.



Now from various links i have established that you have to use DBCC PAGE() with relevant info to get more information, i get back a object and index id, m_objid.



However i dont know how to get the tablename form here, msdn simply says that it is an allocation id not and actual table id, so how can i from here get to table information?



All i am trying to figure out is which table is affected fromt he RID dealock, but that does not seem to be a simple process.



Thanx

View 5 Replies View Related

Table Size Info

Apr 24, 2008

Does TSQL (2005) offer a way to retrieve a given table's total size (data size vs index size)? Would like to be able to get at this info using TSQL (not management studio).

thanks

View 3 Replies View Related

TaskPad Missing Table Info

Apr 5, 2001

Hi:

After I used "copy database" to upgrade a SQL 7 database to SQL 2000, all are fine except the TaskPad view. The table info section is blank. Though we know all tables are in the table object.

Any thought?

David

View 2 Replies View Related

Copy Info From One Table Two Another With Conditions

Oct 25, 2005

I am importing a csv file into a temp table (works fine), now I want to take the data in the temp table based off of the temp id compared to the id of the permanant file.

basically if the record id exists skip to the next line and so forth, I am able to import everything just fine but I cannot get the WHERE condition to acually work.

INSERT INTO TABLE2 (COL1, COL2, COL3) SELECT COL1, COL4, COL7 FROM TABLE1 WHERE table2.col1 <> table1.col1

this is what my actual code is


INSERT INTO USER_INFO (fpu_id,FIRSTNAME, LASTNAME, BOXNUMBER) SELECT id,first,last,box FROM stmailbox WHERE stmailbox.id <> dbo.USER_INFO.USERID

this is the actual error that I get.

Server: Msg 107, Level 16, State 3, Line 2
The column prefix 'USER_INFO' does not match with a table name or alias name used in the query.

-----
thanks for the help

View 1 Replies View Related

Amending Query To Get Info From New Table

Oct 19, 2013

I used to use this code to extract coupon usage from two tables orders and coupons

select distinct o.OrderDate, p.SKU, c.CustomerID, c.CustomerLevelID, c.Email, c.FirstName, c.LastName from customer c
join dbo.Orders_ShoppingCart os with (NOLOCK) on os.CustomerID = c.CustomerID
join dbo.Product p with (NOLOCK) on p.ProductID = os.ProductID
join dbo.Orders o with (NOLOCK) on o.OrderNumber = os.OrderNumber

[code]....

Following a database upgrade the Coupon Code is no longer used. Instead there are two new SQL tables called Promotions and PromotionsUsage.. The link between the two tables are

ID in Promotions

and

PromotionID in PromotionUsage

Both are the same value. So in order to see new orders for coupon usage how would I change this line in the original SQL to retireve this?

View 5 Replies View Related

How To Access The Info Of A Table Created In Other Database

Aug 24, 2006

SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tab_db1'The above query will give the information of the table 'tab_db1' if it is available in the current database (say db1) connected.How can i access the information of a table (say 'tab_db2') which is created under a different database say db2 from the current db connected say db1.I tried the above query with changing the table_name to 'db2..tab_db2'but went invain.sysobjects also dint work..Any help on this will be appreciated..regards,Sathya V

View 2 Replies View Related

Printing Table And Columns Properties Info

Dec 14, 2005

I'm kinda new to SQL. I'm trying to get a print out of a specific table and its columns and column types. Is there a specific command or code that I can use to accomplish this?.

thx,



Newbie.

View 3 Replies View Related

Stored Procedure Returning Info About A Table

Sep 28, 2007

i want to have a user defined function or stored procedure(i don't know which one should be used, anyway!) which returns false if the table has no records, with the table name comes with a parameter.

could you give a little code sample?

thanx

View 4 Replies View Related

Which System Table Holds Job Related Info

Dec 28, 2007

Hi All,

Can anyone help me find out which system table/s are out there that hold SQL Server Job/Agent information?

Thanks!

View 3 Replies View Related

Switching Database's And Retrieving Table, Etc Info

Jul 8, 2007

I have a query that gets the tables, columns, indexes, index_columns for all tables in a data base.

But, I need to be able to select any data base on the server
and then drill down into the tables, columns, etc.

I looked at sys.databases but can't see how to relate that to the
sys.tables to extend my query.

Is there a way?

I've looked at the information_schema area and catalog views
but I don't see a solution yet.

View 7 Replies View Related

Update Certain Fields In User Group Table With New Info

Apr 28, 2014

I've just written a query that successfully brings back the data from one table based on the information from another. Basically we have been given a table of information and need to update certain fields in our user_group table with the new info.

Here is the SELECT statement
SELECT user_group.id, user_group.name, user_group.description, Consultants.description AS Expr10, user_group.btype, user_group.rootmenu,
user_group.intra_user, user_group.primary_g_id, user_group.fname, user_group.lname, user_group.ntlogon, user_group.lang_id,
user_group.[external], user_group.title, user_group.work_tel, user_group.work_fax, user_group.work_ext, user_group.mobile, user_group.sex,
user_group.add2, user_group.add3, user_group.town, user_group.county, user_group.pcode, user_group.private_flag,

[code]....

We want to update the 'description' on the user_group table with the 'description' from the 'consultants' table. To test this, we only want to write the UPDATE so that it changes the description where the name is 'Adam Froth. The UPDATE statement that we've written is

UPDATE user_group
SET user_group.description = Consultants.description
FROM user_group
INNER JOIN Consultants
ON user_group.description = consultants.description
WHERE name like 'Adam Froth%'

but it keeps erroring and saying that it could 'Not be bound'.

View 2 Replies View Related

Updating MSSQL Table With Info From Excel Sheet

May 11, 2007

MSSQL noob here. Sorry guys, but I really need some help.


I have a MSSQL (2000) database and a Products Table. Now, there was three columns used for pricing that I was not able to populate on the initial usage. So I exported the table as an Excel document, and got rid of everything except the UID (unique identifier column) the Name, and the Three columns, so that the customer could take their time in filling out the information.


Ok, so These are what are common to both the MSSQL database and the Excel sheet

column uid = unique id integer
column Name = text
column eBay = number
column PriceGrabber = number
column Amazon = number

So, any idea how I can update my Products Table with this?

Please HELP!

View 18 Replies View Related

How To Make A Temp Table Using Info Fromtwo Tables

Mar 8, 2008

I have one database named StudInfo. It has two tables named StudentInfo, and GradeInfo.
StudentInfo conntains 4 columns. The 1st one is StudentID (PK) int, LastName varchar(10), FirstName varchar(10), and PhoneNumber int.

GradeInfo contains 4 columns also StudentID (FK) int, GradeID varchar(10), Grade int, Date Datetime.

What I would like to know is how using a T-sql query I could make a temp table with studentID, LastName, FirstName, and then the average of all the different types under GradeID. As of right now I have been limiting the names that are put into GradeID to Homework, Daily, Test, Quiz, and Bonus. When I say average I mean the average of all Homeworks under one studentID, and all Daily under one studentID... etc. I would like the info returned for each student in studentID. Allow Nulls has been turned off.

Never assume someone knows what you are talking about.

View 6 Replies View Related

Trigger In Child Table That Required Parent Info

Aug 5, 2007

Hi,
I have tables parent - PurchaseInvoices and child - PurchaseInvoiceDetails. I have trigger in PurchaseInvoiceDetails that would update stock qty based on Location code stored in parent table - PurchaseInvoices upon INSERT/UPDATE/DELETE.

I also set table RI to have cascade delete. I faced problem that, when I delete record in parent table, it would cascade delete child table. Trigger in child table fired and try to update stock qty. However, in this case, trigger unable to locate parent table record anymore.

How to overcome this? I can't move my stock update code to other place since I got to update stock if any changes happen to child table.

Please advice.

View 7 Replies View Related

How To Get The SQL Affinity Mask Value In Sql 2005, And Table That Store This Info

Aug 29, 2006



Hi All

Can u pls tell me How to Get the SQL Affinity Mask value in Sql 2005.

and what is the table/views name that store this info.

for SQL 2000 , we were using following query:

SQLStatement.printf("select c.value from master..sysconfigures c, master..spt_values v,"
"master..syscurconfigs r where v.type = 'C' and v.number = c.config and v.number >= 0 "
"and v.number = r.config and v.name ='affinity mask'");

lErrCode=SQLExecDirect(hStmt,(SQLCHAR*)pszSQLStatement,strlen(pszSQLStatement));

lSQLBindCol(nAffMask);

But With SQL 2005 , we are getting ZERO(0) ROWS SELECTED.

View 1 Replies View Related

Reporting Services :: Two List View - Get Job Info From Table

Oct 2, 2015

I need ssrs report  which  get job info from job table in list control  and other  one is jobid and workdate which also need to be group by and storeproc I am using for this  report is as follow:

ALTER proc [dbo].[VRAJ_JobScheduleReport]            
    @JobID int = null,    @StartDate varchar(25) = null,    @EndDate varchar(25) = nullASSET
NOCOUNT ON SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON DECLARE @sql varchar(max);DECLARE @param varchar(max);DECLARE @where1 varchar(max);DECLARE
@where2 varchar(max);SET @param='';SET @where1='';SET @where2='';IF @JobID IS NOT NULL    BEGIN     
SET @param = @param + 'DECLARE @JobID int; SET @JobID=' + CAST(@JobID AS varchar(50)) + ';';      IF @where1 = ''       
[Code] ...

I need ssrs report which get job info from job table in list control and other one is jobid and workdate which also need to be group by and storeproc I am using for this report is as follow:

ALTER proc [dbo].[VRAJ_JobScheduleReport]
@JobID int = null,
@StartDate varchar(25) = null,
@EndDate varchar(25) = null
AS
SET NOCOUNT ON

[Code] .....

View 5 Replies View Related

Is There A Method To Convert Select * From Table To Select Field1,field2,...fieldn From Table ?

Nov 29, 2007

Is there a method to convert "Select * From Table" to "Select field1,field2,...fieldn From Table" ?
 
Thanks

View 1 Replies View Related

SQL Server 2012 :: Select Statement That Take Upper Table And Select Lower Table

Jul 31, 2014

I need to write a select statement that take the upper table and select the lower table.

View 3 Replies View Related

Declaring A Table Variable Within A Select Table Joined To Other Select Tables In Query

Oct 15, 2007

Hello,

I hope someone can answer this, I'm not even sure where to start looking for documentation on this. The SQL query I'm referencing is included at the bottom of this post.

I have a query with 3 select statements joined together like tables. It works great, except for the fact that I need to declare a variable and make it a table within two of those 3. The example is below. You'll see that I have three select statements made into tables A, B, and C, and that table A has a variable @years, which is a table.

This works when I just run table A by itself, but when I execute the entire query, I get an error about the "declare" keyword, and then some other errors near the word "as" and the ")" character. These are some of those errors that I find pretty meaningless that just mean I've really thrown something off.

So, am I not allowed to declare a variable within these SELECT tables that I'm creating and joining?

Thanks in advance,
Andy



Select * from

(

declare @years table (years int);

insert into @years

select

CASE

WHEN month(getdate()) in (1) THEN year(getdate())-1

WHEN month(getdate()) in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) THEN year(getdate())

END

select

u.fullname

, sum(tx.Dm_Time) LastMonthBillhours

, sum(tx.Dm_Time)/((select dm_billabledays from dm_billabledays where Dm_Month = Month(GetDate()))*8) lasmosbillingpercentage

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

Month(tx.Dm_Date) = Month(getdate())-1

and

year(dm_date) = (select years from @years)

and tx.dm_billable = 1

group by u.fullname

) as A

left outer join

(select

u.FullName

, sum(tx.Dm_Time) Billhours

, ((sum(tx.Dm_Time))

/

((day(getdate()) * ((5.0)/(7.0))) * 8)) perc

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

tx.Dm_Billable = '1'

and

month(tx.Dm_Date) = month(GetDate())

and

year(tx.Dm_Date) = year(GetDate())

group by u.fullname) as B

on

A.Fullname = B.Fullname

Left Outer Join

(

select

u.fullname

, sum(tx.Dm_Time) TwomosagoBillhours

, sum(tx.Dm_Time)/((select dm_billabledays from dm_billabledays where Dm_Month = Month(GetDate()))*8) twomosagobillingpercentage

from

Dm_TimeEntry tx

join

systemuserbase u

on

(tx.owninguser = u.systemuserid)

where

Month(tx.Dm_Date) = Month(getdate())-2

group by u.fullname

) as C

on

A.Fullname = C.Fullname

View 1 Replies View Related

Transact SQL :: Left Join To Get Info From A Table With Foreign Keys

Sep 13, 2015

I am still new to SQL and I am having trouble obtaining the results I need from a query. I have worked on this command for some time and searched the internet but cannot seem to still get it correct.

I have a table called Patient. It's primary key is pat_id.

I have a second table called Coverage. It has no primary key. The foreign keys are pat_id, coverage_plan_id, and hosp_status.

I have a third table called Coverage_History.   It has a primary key consisting of pat_id, hosp_status, copay_priority, and effective_from. 

I want to get the pat_id and all the coverage information that is current.   The coverage table contains specific insurance policy information.   The coverage_history table will indicate the effective dates for the coverage. So the tables could contain something like this:

Patient (pat_id and lname)
P123  Monto
P124  Minto
P125  Dento
P126  Donto

Coverage (pat_id, coverage_plan_id, hosp_status, policy_num)
P123     MED1   OP   A1499
P123     ACT4   OP   H39B 
P124     MED1   OP   C90009
P124     RAC    OP   99KKKK
P124     RAC    OP   99KKKK
P124     MED1   OP   C90009
P125     ARP    OP   G190
P126     BCB    OP   H88

Coverage_History (pat_id, hosp_status, copay_priority, effective_from, coverage_plan_id, effective_to)
P123   OP   1   20150102  MED1    NULL
P123   OP   2   20150102  ACT4    NULL
P124   OP   1   20150203  RAC     20150430
P124   OP   2   20150203  MED1    20150430
P124   OP   1   20150501  MED1    NULL
P124   OP   2   20150501  RAC     NULL
P125   OP   1   20150801  ARP     NULL 
P126   OP   1   20150801  BCB     20160101

select p.pat_id, p.lname, ch.coverage_plan_id, ch.hosp_status, ch.effective_from, ch.effective_to, ch.copay_priority,
       from patient p   
     left join
  ( coverage_history ch left join coverage c on ch.coverage_plan_id = c.coverage_plan_id and ch.patient_id = c.patient_id and
                                   (ch.effective_to is NULL or ch.effective_to >= getdate()
)
         ) on ch.patient_id = p.patient_id
        
    where ( ch.effective_to is NULL or ch.effective_to >= getdate() )
   
So I want to see:

P123  Monto  MED1  OP   20150102    NULL       1
P123  Monto  ACT4  OP   20150102    NULL       2
P124  Minto  MED1  OP   20150501    NULL       1
P124  Minto  RAC   OP   20150501    NULL       2
P125  Dento  ARP   OP   20150801    NULL       1
P126  Donto  BCB   OP   20150801    20160101    1

View 6 Replies View Related







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