T-SQL (SS2K8) :: CTE Query To Find Specific Record?

Sep 18, 2015

I need to build a CTE query to find for the same Cabstamp (document) where i have different Origin.

I know that i can build this with a correlated subquery, but i´am curious about using CTE.

I post sample create Script:

create table #temp (Cabstamp varchar(10), account varchar(10),document varchar(15), origin varchar(2), debit numeric(10,2), credit numeric(10,2), datalc datetime)

insert into #temp (Cabstamp,account,Document, origin, debit, credit, datalc)
select 'ADM12345',111,'CMP-01','FO',1000,0, '20150110'
union
select 'ADM12345',112,'CMP-01','FO', 500, 0,'20150110'
union
select 'ADM12345',6811,'CMP-01','DO',0,1500,'20150110'
union

[code]....

View 5 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Find Best Index For Specific Query

Dec 28, 2014

This is my table:

use tempdb
go
if object_id('Data', 'u') is not null drop table Data
go
with temp as (
select top 10000 row_number() over (order by c1.object_id) Id
from sys.columns c1 cross join sys.columns c2

[code]....

What index would be best for these three queries? With best I mean the execution time, I don't care about additional space.

This is the index I currently use:
create nonclustered index Ix_Data on Data (StateId, PalletId, BoxId, Id)
The execution plan is SELECT (0%) - Stream Aggregate (10%) - Index Scan (90%).

Can this be optimized (maybe to use Index Seek method)?

View 7 Replies View Related

T-SQL (SS2K8) :: Find All Rows From All Tables In A DB For Specific Column?

Mar 28, 2014

I have a DB with some tables and, on certain tables, i've a column named "ID_COMPUTER".

I need to find all the rows where id_computer=<specific_value> from all the tables of my database, when column "ID_COMPUTER" exists.

Pseudo-code would be: select * from db.* where id_computer=<specific_value>

how to write this ?

View 2 Replies View Related

T-SQL (SS2K8) :: Create Index For A Specific Query That Is Used A Lot?

Jul 28, 2014

I am trying to create an index for a specific query that is used a lot.

Unfortunately I am keep getting a clustered index scan. (4.6 mil rows)

Googling "AND" and "OR" is tricky, but did lead met to many articles about filtered indexes.

None of which gave me a clear answer.

How can I make an index for this query?

Here's the code setup

------------------------------------------------------------------------------------------
-- Setup
------------------------------------------------------------------------------------------
IF OBJECT_ID('FilterTbl') IS NOT NULL
DROP TABLE FilterTbl
CREATE TABLE FilterTbl
(
SurroIDInt IDENTITY PRIMARY KEY,
CompIDSmallInt,

[code]....

View 3 Replies View Related

Want To Query One Specific Record From Database Table

Feb 27, 2008

I have two tables in my database: order_id with fields order (text) and comp_ID (int) and another table called customers with comp_ID (int) and company name (text) and other company information fields. The link between the two tables is the comp_ID. With every order that's made the company that made the order is stored with it in the order_id table.  If I type in the order id (text), I want to be able to use the order id to search the order_id table and find out what the comp_ID of the company that made that order is. Then use that comp_ID to pull up the record of company information from the customers table with the same comp_ID. Is there some way to do this in one query? Or how do I accomplish this?  

View 4 Replies View Related

Query To Find SQL Activity At Specific Time?

Mar 23, 2007

Ok, please pardon my complete ignorance; but I am extremely SQL challenged. I manage the server right now and I am the closest thing to a DBA at the moment with this server.

Here is the problem. I have a job that runs every hour and until last week it was running without any problems. Now, once a day it hangs, and I end up having to restart sql to get it to be functional again. I guess I could just kill the spid, but regardless, it's fails.

It doesn't happen at the same time each day. I thought it was from the backups doing a SQL backup job, but I eliminated that possibility. I can't find what is causing the problem, because the SQL logs just stop at the time that this happens. It's like some other job/query is running and taking all the sql server resources. But I can never catch it when it's happening and I have no event logs or SQL logs to go on.

Is there any query that I can run to find what happened around the specific time the job failed to run? I just need to find what process did what when this job stopped working.

Again, I apologize if my lack of SQL knowledge is making me ask dumb questions, but I am really lost.

Thanks in advanced!

View 3 Replies View Related

T-SQL (SS2K8) :: Query To Track Record?

Mar 14, 2014

I am having table which is having 5 columns say A,B,C,D and E. There are chances to change in C,D,E columns. I want to identify if any change happened in the above column and show to user prev value + new value.

i.e. i want to prepare query by using calculated extra 6 column where i want to put change happned in C,D,E columns.

how to do that?

View 5 Replies View Related

T-SQL (SS2K8) :: Query To Find Older Date That Is Less Than 90 Business Days

Feb 12, 2015

select DateAdd(dd,-90,getdate())

It gives the 90 days older date but i want to exclude the weekdays and holidays (saturday ,sunday,holiday)

As we dont have permission to call a function or Sp in high level environments looking for a simple query .

View 1 Replies View Related

How To Create An Copy Of A Certain Record Except One Specific Column That Must Be Different &&amp; Insert The New Record In The Table

Sep 1, 2006

Hi
I have a table with a user column and other columns. User column id the primary key.

I want to create a copy of the record where the user="user1" and insert that copy in the same table in a new created record. But I want the new record to have a value of "user2" in the user column instead of "user1" since it's a primary key

Thanks.

View 6 Replies View Related

T-SQL (SS2K8) :: How To Split One Record Into Multiple Records In Query Based On Start And End Date

Aug 27, 2014

I would like to have records in my Absences table split up into multiple records in my query based on a start and end date.

A random record in my Absences table shows (as an example):

resource: 1
startdate: 2014-08-20 09:00:00.000
enddate: 2014-08-23 13:00:00.000
hours: 28 (= 8 + 8 + 8 + 4)

I would like to have 4 lines in my query:

resource date hours
1 2014-08-20 8
1 2014-08-21 8
1 2014-08-22 8
1 2014-08-23 4

Generating the 4 lines is not the issue; I call 3 functions to do that together with cross apply.One function to get all dates between the start and end date (dbo.AllDays returning a table with only a datevalue column); one function to have these dates evaluated against a work schedule (dbo.HRCapacityHours) and one function to get the absence records (dbo.HRAbsenceHours) What I can't get fixed is having the correct hours per line.

What I now get is:

resource date hours
...
1 2014-08-19 NULL
1 2014-08-20 28
1 2014-08-21 28
1 2014-08-22 28
1 2014-08-23 28
1 2014-08-24 NULL
...

... instead of the correct hours per date (8, 8, 8, 4).

A very simplified extract of my code is:

DECLARE @startdate DATETIME
DECLARE @enddate DATETIME
SET @startdate = '2014-01-01'
SET @enddate = '2014-08-31'
SELECTh.res_id AS Resource,
t.datevalue,
(SELECT ROUND([dbo].[HRCapacityHours] (h.res_id, t.datevalue, t.datevalue), 2)) AS Capacity,
(SELECT [dbo].[HRAbsenceHours] (9538, h.res_id, t.datevalue, t.datevalue + 1) AS AbsenceHours
FROMResources h (NOLOCK)
CROSS APPLY (SELECT * FROM [dbo].[AllDays] (@startdate, @enddate)) t

p.s.The 9538 value in the HRAbsenceHours function refers to the absences-workflowID.I can't get this solved.

View 1 Replies View Related

SQL Server 2012 :: Query Design - Find Most Recent Datetime Record Each Day For A Customer

Apr 2, 2015

So I have a query that need to find the most recent datetime record each day for a customer. So I have a query that looks like this:

SELECT
dhi.[GUID],
dhi.[timestamp],
la.[bundle_id],
dhi.[value]
FROM
[dbo].[DecisionHistoryItem] as dhi WITH(NOLOCK)

[Code] ....

View 4 Replies View Related

How To Get Specific Record From Database

Feb 26, 2008

 HI How to get 100 ,500 and 1000 or (any particular record) record fromDatabase .Shafqat Soomro     

View 3 Replies View Related

How To Select Specific Record.

Oct 24, 2007

Group_Code *****Station_nbr*****Beg_Eff_Date*****End_eff_date

00000002 D01G00733 1/1/2007 8/31/2007
00000002N D01G00733 4/1/2007 8/31/2007
00000002W D01G00733 1/1/2007 12/31/2007


For the report I just want to be able to pick up the first and the last line.

Using dbo.Station_group Table

Thank you for the help

View 14 Replies View Related

T-SQL (SS2K8) :: Track How Many Times A Specific SP Called Every Day

Apr 3, 2014

I need to know /observe for a period like 10 days in a row HOW MANY TIMES a specific Stored Proc is executed on the server. How can I do that? is there a way to precisely know a number of such calls via DMVs?

View 9 Replies View Related

T-SQL (SS2K8) :: Concatenate Specific Values From A Column

May 20, 2014

Give this data set;

declare @BO table (Col1 varchar(50), Col2 varchar(50))
insert into @BO values
('01','009920140516102116'),
('071710811019600001000005',''),
('070534524264000001000005',''),
('001806505517000001000005',''),

[Code] ....

select * from @BO

The 2 digit number that appears on line 1, 7 and 13 (only in this example) i need to have added to the begin of each value below it until the next 2 digit number is encountered. The desired result set would look like:

declare @BOD table (Col1 varchar(50), Col2 varchar(50), col3 varchar(50))
insert into @BOD values
('01','009920140516102116',''),
('071710811019600001000005','','01071710811019600001000005'),
('070534524264000001000005','','01070534524264000001000005'),

[Code] ....

View 7 Replies View Related

T-SQL (SS2K8) :: Replace String After Specific Index

Mar 23, 2015

I have data like below

Potter, James J
Williams, Ted R
Allen, Gary G

I want to remove Middle Name from the output

Potter, James
Williams, Ted
Allen, Gary

My Query:

SELECT
CASE WHEN CHARINDEX(' ', Supervisor, CHARINDEX(' ', Supervisor, 0) + 1) > 0 THEN
REPLACE(Supervisor, SUBSTRING(Supervisor, CHARINDEX(' ', Supervisor, CHARINDEX(' ', Supervisor, 0) + 1), LEN(Supervisor)), '')
ELSE Supervisor END AS NewSupervisor from data d

However, I stumble when Middle Name exists somewhere in the name as Replace function repalces every occurrence of the string. For ex: "Allen, Gary G" becomes "Allen,ary"

Do we have any way to say sql to replace after certain index?

View 3 Replies View Related

T-SQL (SS2K8) :: Specific Column Matching With Nulls

Apr 9, 2015

I'm working on a join between two tables where I only want one row returned... I'm matching on two columns between two tables. One of those columns in the target table could be null. I only want one record returned.

create table #vehicle(id int, vehiclemake varchar(10), vehiclemodel varchar(10), classtype varchar(1))
create table #class(id int, classtype varchar(1), value int)

insert into #vehicle values(1, 'AUDI', 'R8', 'A')
insert into #vehicle values(2, 'AUDI', null, 'B')

insert into #class values(1, 'A', 100)
insert into #class values(2, 'B', 1)

[Code] ....

Using the above example, if VehicleModel is anything other than 'R8' is specified then I want it to return the other class type record.

This is going to be used as a join within a bigger statement, so I'm not sure ordering and returning top 1 is going to work.

View 9 Replies View Related

T-SQL (SS2K8) :: Search Through Rows With Specific Values

Sep 16, 2015

I've a table that stores operationcode for each jobnumber. The jobnumber can have multiple operationcode. From the below DDL, I need to show all the jobs that have operation codes as 2001 and 2002. In the below DDL Jobnumber 80011 has both the operation codes 2001 and 2002 so this job will display on the report.

On the other hand Job 80021 only has operationcode 2001 and I do not want this job to show up on the report.

I need to show all the operationcodes for a job if it has operationcode 2001 and 2002.

USE tempdb;
GO
DECLARE @TEST_DATA TABLE
(
DT_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED
, OperationCodeVARCHAR(10) NOT NULL
, EmployeeCode VARCHAR(10) NOT NULL

[Code] ....

View 9 Replies View Related

Q:Duplicate A Record Except One Or Two Specific Fields Using SQL

Oct 30, 2000

Using Transact-SQL how can I copy all fields except one from one record to another? The field in question being the identity field. Since, this field cannot be duplicated a simple INSERT statement fails. How can I specify an exclusion list of fields?

-Sumit

View 1 Replies View Related

Grabbing First Record Rather Than The Record I Am Trying To Find.

Mar 24, 2007

I tried checking to see if the point at which the reader was, that if it was the record I am looking for to go ahead and add the table data to a label. But for some reason it's only taking the first record in the database and not the one I  thought I was at.[CODE]     public void UpdateMaleHistLbl()    {        SqlConnection conn = new SqlConnection("Server=localhost\SqlExpress;Database=MyFamTree;" + "Integrated Security=True");        SqlCommand comm = new SqlCommand("SELECT * FROM FatherHistTable, MotherHistTable, UsersTable WHERE UsersTable.UserName = @usrnmeLbl ", conn);        comm.Parameters.AddWithValue("@usrnmeLbl", usrnmeLbl.Text);        conn.Open();        SqlDataReader reader = comm.ExecuteReader();        while (reader.Read())        {            string usr = reader["username"].ToString();            usr = usr.TrimEnd();            string pss = reader["password"].ToString();            pss = pss.TrimEnd();            if (usrnmeLbl.Text == usr)            {                if (hiddenpassLbl.Text == pss)                {                    maleHistLbl.Text = reader["GG_Grandfather"] + " > ";                    maleHistLbl.Text += reader["G_Grandfather"] + " > ";                    maleHistLbl.Text += reader["Grandfather"] + " > ";                    maleHistLbl.Text += reader["Father"] + " > ";                    maleHistLbl.Text += reader["Son"] + " > ";                    maleHistLbl.Text += reader["Grandson"] + " > ";                    maleHistLbl.Text += reader["G_Grandson"] + " > ";                    maleHistLbl.Text += reader["GG_Grandson"] + "<br /><br />";                }            }            break; //exit out of the loop since user found        }        reader.Close();        conn.Close();     }}[/CODE]Thanks in advance

View 1 Replies View Related

T-SQL (SS2K8) :: How To Make A Column Comply To A Specific Format

Dec 4, 2014

I need to insert and update a table. One column of the table needs to conform to a format as: XXXXXXX.XXXXX

If any data is not complying to the format an error needs to be thrown.

How to implement this constraint!

View 3 Replies View Related

Is There A Way To Find Our When A Specific Procedure Was Last Executed.

May 29, 2002

Hi,

Is there any system tables or something , which one can query to get when a specific procedure was last run.

Thanks for you help.

View 1 Replies View Related

Newbie: Find And Return A Specific Row Value

Apr 17, 2008

Hi Newbie here,

i am trying to make a highscore table and i would like when the user enters a score for them to be able to see what position they are in the database without having to take out all the data. i have looked at a few methods and was wondering which one is the best solution and how i would go about implementing it

count()
rank()
Indexes

Any response would be greatly appreciated


Puzzled

View 3 Replies View Related

Find Specific Index Size

Mar 27, 2008

We're looking at optimizing some of our tables because we have indexes on columns that are not used. So for example we might have a table that has 6GB of data and 4GB in indexes (according to sp_spaceused). We need to know how much of the 4GB of indexes is consumed by each of the indexes individually. I've tried dbcc showcontig, but that doesn't tell me the amount of space used by the index that I run it for.

Second (and by far not as important), is there a way to determine how much space is being consumed by data in a specific column. The original creator of some of the tables added an incrementing identity column that is used no where in the system. I'd like to be able to say..."If we drop this column we'll save XXX in space."

Knowing the index space is more critical, the column space would be nice but not necessary.

View 2 Replies View Related

Find Out What Tables Contain A Specific Column

Jul 28, 2006

I want to write SQL that will search the tables in a database for a specific column, like this. For instance, I have a column "Unique_ID" that is in many of our tables (hundreds) but not in others and want to find out the tables it is in. It is always the first column.

I tried to find a system stored procdure to do this but couldn't and tried to create a script using the sysobjects and syscolumns tables in the Master db, but came to a roadblock because they don't seem to be related at all.

I would surely appreciate if someone else has already done this!

Thanks!

View 6 Replies View Related

Passing A Specific Cursor Record To A Function

Jul 20, 2005

Hello,Is it possible? Can I select a specific record of the cursor to besent to a seperate function to do all the computations etc.?Regards,VS

View 5 Replies View Related

T-SQL (SS2K8) :: Call Stored Procedure And Obtain Specific Results

Apr 17, 2014

I have a few questions about the following t-sql 2008 r2 sql code listed below that is calling a stored procedure:

DECLARE@return_value int,
@endYear SMALLINT = 2014,
@CustomerID INT = '9999',
@Schedules CHAR(1) = N'C'

EXEC [dbo].[sproom] @endYear
,@CustomerID
,@Schedules

The sql listed above does execute the stored procedure called [dbo].[sproom] successfully and returns all the data all the rows from the stored procedure multiple times. However can you tell me the following:

1. How can I have the stored procedure return distinct rows?
2. I want the stored procedure to return selected columns. I tried using the OUTPUT parameter for some of the columns, but I got the error message, "Procedure or function spHomeroom has too many arguments specified.".

when I change the sql above to:

DECLARE @return_value int,
@endYear SMALLINT = 2014,
@CustomerID INT = '9999',
@Schedules CHAR(1) = N'C',
@CustName varchar(50)
EXEC [dbo].[sproom] @endYear
,@CustomerID
,@Schedules
,@CustName

That is when I get the error message.

A solution might be to change the stored procedure, but I would prefer not to since this is a generic stored procedure that I believe a lot of t-sqls and stored procedures will use.

View 3 Replies View Related

T-SQL (SS2K8) :: Run Block In Stored Procedure Only During Specific Time Frame

May 11, 2015

I have a stored procedure that runs every 5 minutes. I have one block in the procedure that will only run if there are records in a temp table. In addition, I would like this block to run only if the current time is between 0 and 5 minutes past the hour or between 30 and 35 minutes past the hour.

Currently, my block looks like this:
IF OBJECT_ID('tempdb..#tmpClosedPOs') IS NOT NULL
BEGIN

I can get the current minutes of the current time by using:

Select DATEPART(MINUTE,GetDate())

I know that it should be simple, but I'm pretty new at Stored Procedures. How do I alter the IF statement to check for the time and only run the block if it's between the times I stated? I started to DECLARE @Minutes INT, but wasn't sure where to go from there.

View 7 Replies View Related

SQL Server 2012 :: Find First Value Greater Than Specific Value

Dec 19, 2013

I need a query to get the first value greater than a specific threshold value

LoadTemp1 LoadTemp2 LoadTemp3 LoadTemp4 TimeStamp
300 200 100 320 12-10-2013 13:30:29
100 250 113 340 12-10-2013 14:20:12
114 339 209 345 12-10-2013 14:45:01

I need to get the first value >= 340 threshold

I need to make a Benchmark on when the first LoadTemp crosses Threshold of 340 and capture the time.

View 9 Replies View Related

Any Way To Find Out Which SP Is Updating Data In A Specific Table?

Sep 22, 2005

Can you create an UPDATE TRIGGER and use some typeof code to figure out which SP just updated the current table?If not how can i achieve what i want?I tried to run SQL Profiler and i don't understand why i can'tsimply have the Profiler filter events only for the specific database idand the table's object id i chose?What am i doing wrong with SQL Profiler? I was testing thisthrough SQL EM. I had the filters chosen for a specific database idand a specific table's object id, yet when i open another table SQLProfiler captures that information too.Thank you

View 2 Replies View Related

T-SQL (SS2K8) :: Creating Database Where Each Record Is Required To Have Twin Record In Database

May 12, 2014

,I am creating a database where each record is required to have a twin record in the database.These is a type a value and a type b value and both must be present for the record to be valid.

Customer_ID, Order_Type, Product_Code
54, a, 00345
54, b, 00356

Is this something that would have to be done programmatically, or is it possible to create a constraint of some sort to ensure this?

View 8 Replies View Related

SQL Server 2012 :: How To Hide Specific Record(s) From Results

Nov 2, 2015

I have written a SQL statement.There is a table called customer.It contains all customer data with customerid as PK.There is another table called logs and it contains customerid as foreign key and it contains a field to keep more than 90 days older user accounts.That field name is "Checked"

What I need get all records from these 2 tables and remove/hide more than 90 days older customers from record set.See my illustration.

I have written this code but I dont understand how to remove more than 90 days older user from result (because customer table doesnt contain a record called "Checked")

SELECT *
FROM [dbo].[Customers],[dbo].[VIESLog] WHERE [dbo].[VIESLog].[Checked] < DATEADD(day, -90, GETDATE())

View 6 Replies View Related

SQL 2012 :: How To Find Unique Rows Considering Only Specific Columns

Apr 18, 2014

write a query which retrieves only unique rows excluding some columns.

IdStatusmanager Team Comments Proj number Date
19391New XUnassigned One 3732.0 16-Apr-14
19392Can YCustomer Two 3732.0 17-Apr-14
19393Can YCustomer Two 3732.0 17-Apr-14
19394Can YCustomer One 3732.0 18-Apr-14
19395New YCustomer One 3732.0 19-Apr-14
19396New YCustomer One 3732.0 21-Apr-14
19397New ZCustomer One 3732.0 20-Apr-14

In the above table project number and id shouldn't be considered and I should get the unique rows considering rest of columns and sorted based on date. Expected result is

IdStatusmanager Team Comments Proj number Date
19391New XUnassigned One 3732.0 16-Apr-14
19392Can YCustomer Two 3732.0 17-Apr-14
19394Can YCustomer One 3732.0 18-Apr-14
19395New YCustomer One 3732.0 19-Apr-14
19397New ZCustomer One 3732.0 20-Apr-14
19396New YCustomer One 3732.0 21-Apr-14

View 4 Replies View Related







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