SQL 2012 :: How To Update And Join Table With Cursor

Jul 15, 2014

I have table A

|account | Unmort |
| A |10.000.000 |

and a Table B

|account| Jenis | Nominal | Unmort |Total|
-------------------------------------------
| A | 021 | 200.000| - | - |
| A | 028 | 3.200.000| - | - |
| A | 023 | 7.200.000| - | - |

how to update to be like this??

|account| Jenis |Nominal | Unmort |Total |
| A | 021 |200.000 | - |200.000 |
| A | 028 |3.200.000 | 2.800.000 |400.000 |
| A | 023 |7.200.000 | 7.200.000 | 0 |

for this type of account number jenis 021 Field Unmort Fill set= 0 and Field Total must not be a minus...

View 3 Replies


ADVERTISEMENT

One Statement Update - Join, No Cursor ?

Jul 20, 2005

HI AllI have a process that I am trying to accomplish with one statement. Icannot think of any way to do it other than using a cursor.I was wondering if anyone could point me in the right direction.I want to update the Domain in Table A with the Domain in Table Bwhere A.Account = B.Account with the highest rank.----------------------------------Table A--------------------------------------------------------------------Account|Domain--------------------------------------------------------------------Micorsoft|null----------------------------------IBM|null-------------------------------------------------------------TAble B--------------------------------------------------------------------------------------------------------------------------Account|Domain|Rank--------------------------------------------------------------------------------------------------------------------------Micorsoft|microsoft.com|9-------------------------------------------------------------Micorsoft|yahoo.com|2-------------------------------------------------------------Micorsoft|hotmail.com|1Thanks!!!

View 6 Replies View Related

Join Cursor With Table Outside Of Cursor

Sep 25, 2007

part 1

Declare @SQLCMD varchar(5000)
DECLARE @DBNAME VARCHAR (5000)

DECLARE DBCur CURSOR FOR
SELECT U_OB_DB FROM [@OB_TB04_COMPDATA]

OPEN DBCur
FETCH NEXT FROM DBCur INTO @DBNAME


WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @SQLCMD = 'SELECT T0.CARDCODE, T0.U_OB_TID AS TRANSID, T0.DOCNUM AS INV_NO, ' +
+ 'T0.DOCDATE AS INV_DATE, T0.DOCTOTAL AS INV_AMT, T0.U_OB_DONO AS DONO ' +
+ 'FROM ' + @DBNAME + '.dbo.OINV T0 WHERE T0.U_OB_TID IS NOT NULL'
EXEC(@SQLCMD)
PRINT @SQLCMD
FETCH NEXT FROM DBCur INTO @DBNAME

END

CLOSE DBCur
DEALLOCATE DBCur


Part 2

SELECT
T4.U_OB_PCOMP AS PARENTCOMP, T0.CARDCODE, T0.CARDNAME, ISNULL(T0.U_OB_TID,'') AS TRANSID, T0.DOCNUM AS SONO, T0.DOCDATE AS SODATE,
SUM(T1.QUANTITY) AS SOQTY, T0.DOCTOTAL - T0.TOTALEXPNS AS SO_AMT, T3.DOCNUM AS DONO, T3.DOCDATE AS DO_DATE,
SUM(T2.QUANTITY) AS DOQTY, T3.DOCTOTAL - T3.TOTALEXPNS AS DO_AMT
INTO #MAIN
FROM
ORDR T0
JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN DLN1 T2 ON T1.DOCENTRY = T2.BASEENTRY AND T1.LINENUM = T2.BASELINE AND T2.BASETYPE = T0.OBJTYPE
LEFT JOIN ODLN T3 ON T2.DOCENTRY = T3.DOCENTRY
LEFT JOIN OCRD T4 ON T0.CARDCODE = T4.CARDCODE
WHERE ISNULL(T0.U_OB_TID,0) <> 0
GROUP BY T4.U_OB_PCOMP, T0.CARDCODE,T0.CARDNAME, T0.U_OB_TID, T0.DOCNUM, T0.DOCDATE, T3.DOCNUM, T3.DOCDATE, T0.DOCTOTAL, T3.DOCTOTAL, T3.TOTALEXPNS, T0.TOTALEXPNS


my question is,
how to join the part 1 n part 2?
is there posibility?

View 1 Replies View Related

How Do U Update A Row In A Table Using Cursor ?

Mar 11, 2008

How do you do this by using this cursor mechanisum ? and which type of cursor is best to do that ?

View 1 Replies View Related

T-SQL (SS2K8) :: Cursor Table Update

May 6, 2015

DECLARE @id VARCHAR(10)
DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT [ServersList] AS 'ID'
FROM dbo.Servers

[code]...

How do loop a table server(serverlist,flag) table with these 2 columns.And ping each of the servers in the table and update the flag column to '1' if ping has been successfull or flag to '0' if ping has been unsuccessfull.

View 1 Replies View Related

Cursor Count Loop - Update Table

Jul 6, 2000

I am importing a text file that list invoice columns. The invoice detail table needs the line items to be listed with sequential numbers. I import the file to a temp table to do the work in and I know I need to have the cursor do loop through and count, however, I have no more hair to pull out.

The table looks something like this.

inv# SKU
1001 ABC123
1001 DEF456
1001 GHI789
1002 123DEF
1002 456GHI
1002 876HGT

I need the cursor to go through and number each line, something like this.

inv# SKU Line#
1001 ABC123 1
1001 DEF456 2
1001 GHI789 3
1002 123DEF 1
1002 456GHI 2
1002 876HGT 3

Any help is greatly appriciated.

Thanks

View 1 Replies View Related

SQL 2012 :: Calling Proc For Each Row In A Table Without Using Cursor

Apr 14, 2015

I have a table that has the following data

ID
---
101
102
105
108
124
189

I need to call a stored proc for each of the IDs above. Our existing code which has a cursor to loop through the table and call the proc for each value is proving to be a performance nightmare. Is there an alternate method that I can use to avoid cursor and make it more efficient?

View 2 Replies View Related

SQL Server 2012 :: Call Stored Proc Once Per Each Row Of A Table Without Using CURSOR

Jul 10, 2014

I have a situation where I need to call a stored procedure once per each row of table (with some of the columns of each row was its parameters). I was wondering how I can do this without having to use cursors.

Here are my simulated procs...

Main Stored Procedure: This will be called once per each row of some table.

-- All this proc does is, prints out the list of parameters that are passed to it.

CREATE PROCEDURE dbo.MyMainStoredProc (
@IDINT,
@NameVARCHAR (200),
@SessionIDINT
)
AS
BEGIN

[Code] ....

Here is a sample call to the out proc...

EXEC dbo.MyOuterStoredProc @SessionID = 123

In my code above for "MyOuterStoredProc", I managed to avoid using cursors and was able to frame a string that contains myltiple EXEC statements. At the end of the proc, I am using sp_executesql to run this string (of multipl sp calls). However, it has a limitation in terms of string length for NVARCHAR. Besides, I am not very sure if this is an efficient way...just managed to hack something to make it work.

View 9 Replies View Related

SQL Server 2012 :: Removing Cursor In Table Valued Function

Oct 16, 2015

I need removing cursor in my table valued function with alternate code.

ALTER FUNCTION [dbo].[eufn_e5_eSM_SE_GetCurrentContentForContainer]
(
@containerSqlId SMALLINT,
@containerIncId INT
)
RETURNS @Results TABLE

[Code] ....

View 2 Replies View Related

SQL Server 2012 :: Join To Find All Records From One Table That Do Not Exist In Other Table

Apr 29, 2014

I have table 'stores' that has 3 columns (storeid, article, doc), I have a second table 'allstores' that has 3 columns(storeid(always 'ALL'), article, doc). The stores table's storeid column will have a stores id, then will have multiple articles, and docs. The 'allstores' table will have 'all' in the store for every article and doc combination. This table is like the master lookup table for all possible article and doc combinations. The 'stores' table will have the actual article and doc per storeid.

What I am wanting to pull is all article, doc combinations that exist in the 'allstores' table, but do not exist in the 'stores' table, per storeid. So if the article/doc combination exists in the 'allstores' table and in the 'stores' table for storeid of 50 does not use that combination, but store 51 does, I want the output of storeid 50, and what combination does not exist for that storeid. I will try this example:

'allstores' 'Stores'
storeid doc article storeid doc article
ALL 0010 001 101 0010 001
ALL 0010 002 101 0010 002
ALL 0011 001 102 0011 002
ALL 0011 002

So I want the query to pull the one from 'allstores' that does not exist in 'stores' which in this case would the 3rd record "ALL 0011 001".

View 7 Replies View Related

Update Table With JOIN

Jun 2, 2004

Ok, I have tried this a million ways, and I am just stumped...

I have a access statement I am trying to convert to a T-SQL Statement.. There is no reason I should be having such a hard time with a simple query. Please Help!


UPDATE Tbl1
INNER JOIN Tbl2 ON Tbl1.ID = Tbl2.ID
SET tbl1.Field1 = tbl2.Field1

View 2 Replies View Related

Update One Table Using Join With Another?

Mar 13, 2006

I have a table with date values that are currently null.

I've created a query that identifies the dates that should go into the date field for the table. I'll call the table "shipping" and the SQL Query, "query".


query has the following fields:
CN int
CSN int
shipdate datetime

shipping has the following fields that are relavent:
CN int
CSN int
shipped_date datetime

I want to update shipping, setting shipping.shipped_date=query.shipdate
where query.cn=shipping.cn and query.csn=shipping.csn

How do I word it to get a proper update using query analyzer?

View 3 Replies View Related

How To Use Inner Join In Update Method For 1 Table

Aug 23, 2007

i need to use inner join while updating..
im using only one table..


rajesh

View 2 Replies View Related

Update Table Using Join In Sql Server 2005

Nov 29, 2007

hi all,
i want to update two tables using join . i'm also using stored procedure . also i'm using sql server 2005. i 've written a stored procedure but i'm getting errors.
here is my code and error:
create proc bannersupdate(@bannerid int,@bannername varchar(100),@entereddate varchar(10),@validfromdate datetime,@validtodate datetime,@imagesize varchar(20),@imageweight smallint,@imageurl varchar(200))
as
begin
update Banner.BannerName,Banner.EnteredDate,Banner.ValidFromDate,Banner.ValidToDate,BannerImage.ImageSize,BannerImage.ImageWeight,BannerImage.ImageURL
set Banner.BannerName=@bannername,Banner.EnteredDate=@entereddate,Banner.ValidFromDate=@validfromdate,Banner.ValidToDate=@validtodate,BannerImage.ImageSize=@imagesize,BannerImage.ImageWeight=@imageweight,BannerImage.ImageURL=@imageurl
from Banner join BannerImage on Banner.BannerID=BannerImage.BannerID where Banner.BannerID=@bannerid
end
Msg 102, Level 15, State 1, Procedure bannersupdate, Line 4
Incorrect syntax near ','.
any one who knows how to solve this plese send me the correct code..
thanks
swapna

View 1 Replies View Related

SP With Inner Join - Update Table Value (Single Column)

Oct 16, 2015

I'm trying to do the following:

update a tables value(a single column), based on a query of another database, using a common column.

Here's what I've cooked up so far:

Declare @trackingNo nvarchar (50)
Set @trackingNo =
(
select tracking_no from P21_Shipping.dbo.shipping_data t1
inner join P21.dbo.oe_hdr t2 on t1.order_no = t2.order_no

[Code] ...

print @trackingNoThe error it's returning is:

Msg 512, Level 16, State 1, Line 3
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

So, I'm wanting to query Shipping_data for order_No that matches the same orderNo column value in P21 Database(oe_hdr table), then update P21 oe_hdr table with "trackingNo from Shipping_data

View 8 Replies View Related

Compare Two Table And Update - Join Statement

Apr 27, 2015

I compare two table with JOIN statement. Now I would like to update one of them base on result. How it to do?

View 2 Replies View Related

Transact SQL :: Update Table Based On Join

Sep 7, 2015

I have table A with colums ID and Product. I have table B with ID (same as table A) and revenue of product.

I need to update the field Product of table A with the revenue of table B.

I'm confuse with the update joining both tables. I tried this, but obviously has an error:

Update A set Product=B.Revenue where A.ID=B.ID

View 6 Replies View Related

SQL 2012 :: Creating A Table Based On Non-Join

Oct 21, 2014

I have 2 tables that I need to merge let me explain. I have a range of product ID's that have a product grouping of * meaning all product groups. So I have a table with products and one with around 100 groups

ProdID ProdGrp
-------- ---------
11 *
12 *

ProdGrp ProdGrpDesc
--------- ---------------
A Prod Group A
B Prod Group B
C Prod Group C

I need a table which looks like the below but I have no joining mechanism

ProdID ProdGrp
-------- ---------
11 A
11 B
11 C
12 A
12 B
12 C

View 3 Replies View Related

SQL 2012 :: JOIN If Specific Table Exists

Jun 9, 2015

I have standard SQL query for clients, but sometimes a client does not have a specific table.

How do I deal with that? (creating the table is not an option)

SELECT
A.Col1
,A.Col2
,B.Col3
--> Col 50

FROM
TableA A Join
TableB B ON A.ColA = B.ColA

Suppose in some cases TabelB does not exist. How do I make sure the rest of the query runs okay and does not result in an error?

View 4 Replies View Related

SQL 2012 :: Possible To Find All Tables That Has A Join With Given Table In Database

Jan 7, 2015

I need to find all tables which has a join (either inside an sp, view, etc) with my given table in a db.

sys.dm_sql_referencing_entities doesn't work here.

Note: i dont want to identify by FK References, for 2 reasons:

1) tables might not met with a join (just FK was defined)
2) sometimes, a join happened between tables, without an FK defined

View 1 Replies View Related

SQL Server 2012 :: Multiple Level Join On Same Table?

Oct 10, 2015

i have below queries each select is fetching records at one level. Is there a way i can write single query to get to nth level (recursion) instead joining same table 10 times (i don't know in some cases there is may be next level) I stopped at 10th level now. In below example i gave only two levels.

SELECT Distinct
a.Col1 AS EmpID,
a.Col1 AS EmpID,
a.Col2 AS Emp_guid,
a.Col2 AS Emp_guid,
case

[code].....

View 1 Replies View Related

SQL Server 2012 :: Update Table From Variable Table Column?

Oct 6, 2014

I am trying to use a stored procedure to update a column in a sql table using the value from a variable table I getting errors because my syntax is not correct. I think table aliases are not allowed in UPDATE statements.

This is my statement:

UPDATE [dbo].[sessions_teams] stc
SET stc.[Talks] = fmt.found_talks_type
FROM @Find_Missing_Talks fmt
WHERE stc.sessionid IN (SELECT sessionid FROM @Find_Missing_Talks)
AND stc.coupleid IN (SELECT coupleid FROM @Find_Missing_Talks)

View 2 Replies View Related

SQL Server 2012 :: Update Table Using CTE Or Using Inner Query On Same Table

Jul 29, 2015

To avoid locking/blocking, or in transaction scope, we are trying make a common practice of writing coide for update commands in our all SPs based on primary key columns in where clause. I have a following scenario...

UPDATE [dbo].[TL_CST_Locker_Issuance] SET
[isActive] = 0
WHERE
LockerIssuanceId IN (SELECT LockerIssuanceId

[Code] ...

What is the better approach and should be followed to avoid locks and gain performance or best approach.

View 7 Replies View Related

SQL Server 2012 :: Stored Procedure - How To Join Another Table Into Select Statement

Jan 7, 2014

I have a stored procedure that I have written that manipulates date fields in order to produce certain reports. I would like to add a column in the dataset that will be a join from another table (the table name is Periods).

The structure of the periods table is as follows:

[ID] [int] NOT NULL,
[Period] [int] NULL,
[Quarter] [int] NULL,
[Year] [int] NULL,
[PeriodStarts] [date] NULL,
[PeriodEnds] [date] NULL

The stored procedure is currently:

USE [International_Forecast_New]
GO
/****** Object: StoredProcedure [dbo].[GetOpenResult] Script Date: 01/07/2014 11:41:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

[Code] ....

What I need is to add the period, quarter and year to the dataset based on the "Store_Open" value.

For example Period 2 looks like this
Period Quarter Year Period Start Period End
2 1 20142014-01-27 2014-02-23

So if the store_open value is 02/05/2014, it would populate Period 2, Quarter 1, Year 2014.

View 1 Replies View Related

SQL Server 2012 :: How To Join Tables To Get Only Record With Specific Field Value In A Table

Feb 6, 2015

I have a table of "applicants" with unique applicant id and another table "reviews" with reviews which has unique id and Emplid and contains general program name like Math and then may contain 3 addition rows for specific program like Calculus, algebra, geometry etc.

There may or may not be a record for each applicant id in table reviews or there can be 1 or more than one record in reviews based on level of review( General or Specific).

All the general reviews has “Math” as Program_code but if there are more reviews, they can have Program_code like “Cal” , “Abr”, “Geo”

I want to join the tables so I can get all the records from both the tables where Program_code in reviews table is “Math” only.

That is I want to join the table and get all the records from reviews table where the program_code is “Math” only
How can I do that?

View 6 Replies View Related

SQL Server 2012 :: Set Based Method To Insert Missing Records Into Table - Right Join Not Work

Apr 24, 2014

I have table A (EmployeeNumber, Grouping, Stages)
and
Table B (Grouping, Stages)

Table A could look like the following where the multiple employees could have multiple types and multiple stages.

EmployeeNumber, Type, Stages
100, 1, Stage1
100, 1, Stage2
100, 2, Stage1
100, 2, Stage2
200, 1, Stage1
200, 2, Stage2

Table B is a list of requirements that each employee must have. So every employee must have a type 1 and 2 and the associated stages listed below.

Type, Stage
1, Stage1
1, Stage2
2, Stage1
2, Stage2
2, Stage3
2, Stage4

So I know that each employee should have 2 Type 1's and 4 Type 2's. I hope that makes sense, I'm trying to change my data because ours is very proprietary.

I need to identify employees who do not have all their stages and list the stages they are missing. The final report should only have employees and the associated missing types and stages.

I do a count by employee to see how many types they have to identify the ones that don't have all the types and stages.

My count would look something like this:

EmployeeNumber Type Total
100, 1, 2
100, 2, 2
200, 1, 1
200 1, 2

So I know that employee 100 should have 2 more Type 2's and employee 200 should have 1 more Type 1 and 2 more Type 2's based on the required list.

The problem I'm having is taking that required list and joining to my list of employees with missing data and pulling from it the types and stages that are missing by employee. I thought I could get a list of the employees that are missing information and right join it to the required list where the missing records would be nulls. But, that doesn't work because some employees do have the required information and so I'm not getting any nulls returned.

View 9 Replies View Related

SQL Server 2012 :: Update ID In The Table?

Oct 11, 2014

I wrote query to update id int(1,1) to some value but its not giving me the result. Is it not possible to update id on the table.

View 7 Replies View Related

SQL 2012 :: Update A Table Using Where Clause?

Oct 29, 2015

I have a temporary table #Temp with, among others, a column CountryCode and a column Lastname.I would like to change the ü that appears in some names to u (u umlaut to a plain u), but only for those that have the nationality 'Ned'

My code so far:

Update #Temp
set LastName = replace(Lastname, 'ü', 'ue') WHERE CountryCode = 'Ned'

This code deletes all entries in the column Lastname

I think it must be easy, but I keep staring at the code.

What to do?

View 5 Replies View Related

SQL Server 2012 :: How To Update One Column Value To Another In Same Table

Jun 21, 2014

my table payment_details structure is

payment_id payment_code
1 null
2 null
3 null
4 null

here payment_id is a primary key and i need to update the whole payment_id column to payment_code column.so i just tried the below query

update payment_details
set payment_code = payment_no
where payment_code is null

but it shows subquery error?

View 3 Replies View Related

SQL Server 2012 :: Update Record In Table?

Nov 7, 2014

To see where is the problem I am trying to count rows in the database.First I create a table A with 2 columns namely tablename, rowbefore and rowafter and I insert records in it as below.

INSERT INTO A
SELECT TableName = o.name, '', Rows = max(i.rows) FROM sysobjects o
INNER JOIN sysindexes i ON o.id = i.id
WHERE xtype = 'u' AND OBJECTPROPERTY(o.id,N'IsUserTable') = 1
GROUP BY o.name
ORDER BY o.name
Then I update rowbefore with rowafter as below.
UPDATE A SET rowbefore = rowafter

Now I launch my application with update records in the database.Then I am trying to update rowafter with new records as below.

UPDATE A
SET rowafter = (SELECT max(sysindexes.rows) FROM sysobjects
INNER JOIN sysindexes ON sysobjects.id = sysindexes.id
WHERE xtype = 'u' AND OBJECTPROPERTY(sysobjects.id,N'IsUserTable') = 1 AND A.tablename = sysobjects.name)

Does this update really update my column rowafter or not?

View 2 Replies View Related

SQL Server 2012 :: UPDATE Using Table Alias

Sep 21, 2015

I have some stored procedures that do updates using table aliases, like this:

UPDATE TableAlias
SET ColVal = 1
FROM RealTable AS TableAlias
WHERE TableAlias.ColVal <> 1

This allows me to include joins and stuff in the update (not shown) and make it all more readable for me.

It all works fine, and the SSMS parser says it's fine. But I also have another script which looks at sys.sql_expression_dependencies and sys.objects to find stored procedures with invalid object references (see below), and it's understandably saying that all of the above type stored procedures have invalid references.

SELECT
OBJECT_NAME(DEP.referencing_id) AS referencing_name,
DEP.referenced_entity_name
FROM sys.sql_expression_dependencies AS DEP
WHERE
-- Only validate local references:
(
DEP.referenced_database_name = DB_NAME()

[Code] ....

So I have a couple questions.

1. Is the UPDATE syntax I'm using kosher?
2. Can you recommend any updates to my stored procedure validation script that will better accommodate table aliases like mine?

View 5 Replies View Related

SQL Server 2012 :: Update Table Using Variable From Another Query?

Apr 3, 2014

I want to update one table with the value from variable using a set based approach.

so the line

>> select @List = coalesce(@list + ',','') + cast(id as varchar(10)) + cast(feetype as varchar(25))

works fine but I want to take @list and use it to update my customers table. here is the full code.

create table customers
(custid int, fee_history varchar(max))
insert into customers
(custid
, fee_history

[code]....

View 5 Replies View Related

SQL Server 2012 :: Table Variable Update Column

May 29, 2014

I am writing a query to update table variable. It is throwing me some error.

I have a table variable declared and inserted the data with three columns. I want to update col1 of that table variable when the second column of that table variable= one column from a physical table

update @MYtabvar set @Mytabvar.LatestDate=B.LatestDate from TableB B where @Mytabvar.id=B.ID

View 9 Replies View Related







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