Error Condition For Updates
Jan 29, 2004
Hi,
I have a series of Updates that I perform on 7 tables. I would like to execute these updates on a nighly basis via a job. I have the update statements lined up in a stored proc.
So I have -
Create Proc Update
AS
SET NOCOUNT ON
DECLARE @RETURNVALUE int
DECLARE @ERRORMESSAGETXT varchar(510)
DECLARE @ERRORNUM int
set @RETURNVALUE = 0
BEGIN ---Start here
Update table1
Update table2
.
.
.
Update table7
SELECT @ERRORNUM = @@ERROR
IF @ERRORNUM = 0
SELECT @RETURNVALUE = 0
ELSE
BEGIN
SELECT @ERRORMESSAGETXT = description FROM [master].[dbo].[sysmessages]
WHERE error = @@ERROR
RAISERROR (@ERRORMESSAGETXT, 16, 1)
SELECT @RETURNVALUE = 1
END
RETURN @RETURNVALUE
END --- END HERE
---
Is the error checking at the appropriate place? Should I have error conditions after every update? If yes then what condition do I check for?
Thanks
View 4 Replies
ADVERTISEMENT
Apr 19, 2007
Dear friends,
I'm having a problem... maybe it's very simple, but with soo many work, right now I can't think well...
I need to filter rows in a dataflow...
I created a condition spli to that... maybe there is a better solution...
And the condition is: Datex != NULL(DT_DATE)
(Some DATE != NULL)
[Eliminar Datex NULL [17090]] Error: The expression "Datex != NULL(DT_DATE)" on "output "Case 1" (17123)" evaluated to NULL, but the "component "Eliminar Datex NULL" (17090)" requires a Boolean results. Modify the error row disposition on the output to treat this result as False (Ignore Failure) or to redirect this row to the error output (Redirect Row). The expression results must be Boolean for a Conditional Split. A NULL expression result is an error.
What is wrong??
Regards,
Pedro
View 4 Replies
View Related
Apr 27, 2005
I have the following stored procedure:
CREATE PROCEDURE user1122500.sp_modifyOrganization(@Name nvarchar(100),@Location nvarchar(50),@Url nvarchar (250),@Org_Type nvarchar (50),@Par_Org_Id uniqueidentifier,@Row_Id uniqueidentifier,@Error_Code int OUTPUT,@Error_Text nvarchar(768) OUTPUT)ASDECLARE @errorMsg nvarchar(512)DECLARE @spName sysname
SELECT @spName = Object_Name(@@ProcID)SET @Error_Code = 0
IF @Url > ' ' BEGIN UPDATE USER1122500.ORGANIZATION SET URL = @Url ,UPDATED = GETDATE() WHERE ROW_ID = @Row_Id IF @@error <> 0 BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id, N'URL', @Url SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code) RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg) RETURN(@@error) END END
IF @Org_Type > ' ' BEGIN UPDATE USER1122500.ORGANIZATION SET ORG_TYPE = @Org_Type ,UPDATED = GETDATE() WHERE ROW_ID = @Row_Id IF @@error <> 0 BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id, N'ORG_TYPE', @Org_Type SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code) RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg) RETURN(@@error) END END
IF @Par_Org_Id IS NOT NULL BEGIN UPDATE USER1122500.ORGANIZATION SET PAR_ORG_ID = @Par_Org_Id ,UPDATED = GETDATE() WHERE ROW_ID = @Row_Id IF @@error <> 0 BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id, N'PAR_ORG_ID', @Par_Org_Id SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code) RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg) RETURN(@@error) END END
IF @Name > ' ' OR @Location > ' ' BEGIN
IF EXISTS (SELECT ROW_ID FROM USER1122500.ORGANIZATION WHERE NAME = @Name AND LOCATION = @Location) BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'NAME', @Name, N'LOCATION', @Location SET @Error_Code = 55004 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code)-- RAISERROR(@Error_Text, 10, 1, @spName, @Error_Code, 'ORGANIZATION', @errorMsg) SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'sp_name',@spName)) SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'err_cd',@Error_Code)) SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'tbl_name','ORGANIZATION')) SELECT @Error_Text = (SELECT REPLACE(@Error_Text,'err_msg',@errorMsg)) RETURN(@Error_Code) END
IF @Name > ' ' BEGIN UPDATE USER1122500.ORGANIZATION SET NAME = @Name ,UPDATED = GETDATE() WHERE ROW_ID = @Row_Id IF @@error <> 0 BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id, N'PAR_ORG_ID', @Name SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code) RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg) RETURN(@@error) END END
IF @Location > ' ' BEGIN UPDATE USER1122500.ORGANIZATION SET LOCATION = @Location ,UPDATED = GETDATE() WHERE ROW_ID = @Row_Id IF @@error <> 0 BEGIN EXEC user1122500.sp_tagValueList @errorMsg OUTPUT, N'ROW_ID', @Row_Id, N'LOCATION', @Location SET @Error_Code = 51002 -- Error Message as created in the ERROR_LIST table SELECT @Error_Text = (SELECT DESC_TEXT FROM USER1122500.ERROR_LIST WHERE ERROR_CODE = @Error_Code) RAISERROR(@Error_Text, 11, 1, @spName, @@error, 'ORGANIZATION', @errorMsg) RETURN(@@error) END END
ENDGO
This is the code that runs it:
string strSP = "sp_modifyOrganization";
SqlParameter[] Params = new SqlParameter;
string strParOrgID = null;
if (this.ddlParentOrg.SelectedItem.Value != "")
{
strParOrgID = this.ddlParentOrg.SelectedItem.Value;
}
Params[0] = new SqlParameter("@Name", txtName.Text);
Params[1] = new SqlParameter("@Location", this.txtLocation.Text);
Params[2] = new SqlParameter("@Url", this.txtURL.Text);
Params[3] = new SqlParameter("@Org_Type", this.txtOrgType.Text);
//Params[4] = new SqlParameter("@Par_Org_Id", strParOrgID);
Params[4] = new SqlParameter("@Par_Org_Id", "CA1FBC83-D978-48F1-BCBC-E53AD5E8A321".ToUpper());
Params[5] = new SqlParameter("@Row_Id", "688f2d10-1550-44f8-a62c-17610d1e979a".ToUpper());
// Params[5] = new SqlParameter("@Row_Id", lblOrg_ID.Text);
Params = new SqlParameter("@Error_Code", -1);
Params[7] = new SqlParameter("@Error_Text", "");
Params[4].SqlDbType = SqlDbType.UniqueIdentifier;
Params[5].SqlDbType = SqlDbType.UniqueIdentifier;
Params.Direction = ParameterDirection.Output;
Params[7].Direction = ParameterDirection.Output;
try
{
this.dtsData = SqlHelper.ExecuteDataset(ConfigurationSettings.AppSettings["SIM_DSN"], CommandType.StoredProcedure, strSP, Params);
if (Params.Value.ToString() != "0")
{
lblError.Text = "There was an error: " + Params.Value.ToString()+ "###" + Params[7].Value.ToString();
lblError.Visible = true;
}
}
//catch (System.Data.SqlClient.SqlException ex)
catch (System.InvalidCastException inv)
{
lblError.Text = lblOrg_ID.Text + "<br><br>" + inv.ToString() + inv.Message + inv.StackTrace + inv.HelpLink;
lblError.Visible = true;
}
catch (Exception ex)
{
lblError.Text = lblOrg_ID.Text + "<br><br>" + ex.ToString();
lblError.Visible = true;
// return false;
}
This is the exception being generated:
System.InvalidCastException: Invalid cast from System.String to System.Guid. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SqlClient.SqlCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(SqlConnection connection, CommandType commandType, String commandText, SqlParameter[] commandParameters) in C:Program Files\_vsNETAddOnsMicrosoft Application Blocks for .NETData Access v2CodeVBMicrosoft.ApplicationBlocks.DataSQLHelper.vb:line 542 at Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(String connectionString, CommandType commandType, String commandText, SqlParameter[] commandParameters) in C:Program Files\_vsNETAddOnsMicrosoft Application Blocks for .NETData Access v2CodeVBMicrosoft.ApplicationBlocks.DataSQLHelper.vb:line 458 at development.youthleadercert.com.share.ascx.organizationForm.btnAdd_Click(Object sender, EventArgs e) in c:documents and settingsmark rubinvswebcachedevelopment.youthleadercert.comshareascxorganizationform.ascx.cs:line 352
I have no idea what field is even causing the error, nor do I see that I'm even using a GUID field. I've been stuck on this for 2 days. Any help?
View 2 Replies
View Related
Mar 12, 2007
Hi,
I tried to instal KB921896 and get: updates did not install error code 0x3b0c.
In one of the summaries, I have
Product Installation Status
Product : Express Database Services Adv (WSUS)
Product Version (Previous): 2047
Product Version (Final) :
Status : Failure
Log File : C:Program FilesMicrosoft SQL Server90Setup BootstrapLOGHotfixSQL9Express_Hotfix_KB921896_SQLEXPR_ADV.EXE
SQL Express Features : SQL_Data_Files,SQL_Engine,SQL_SharedTools
Error Number : 15116
Error Description : Unable to install Windows Installer MSI file
How do I fix this?
thanks
View 3 Replies
View Related
Feb 9, 2006
For example..
select * from mytable where MyNum = 7
If this brings back more than 1 row, I want to display a message that says,
Print 'There is more than one row returned'
Else (If only 1 row returned), I don't want to print anything.
Can I do this? Thx!
View 1 Replies
View Related
Jun 22, 2015
I am trying to write an visibility function to have message shown based on two different IIF conditions:
If behavior is to Add a customer ( if message =NAME ALREADY EXISTS, return " NAME ALREADY EXISTS", otherwize return " NAME CREATED")If behavior is to Delete a customer (( if message =NAME DOES NOT EXIST, return "NAME DOES NOT EXIST", otherwize return "NAME SUCCESSFULLY DELETED")
I tried the following which doesn't work:
=IIF((UCase(First(Fields!Message.Value, "DataSetName")) = "NAME ALREADY EXISTS"), "WARNING: NAME ALREADY EXIST", "NAME CREATED"),
IIF((UCase(First(Fields!Message.Value, "DataSetName")) = " NAME DOES NOT EXIST"), "WARNING: NAME DOES NOT EXIST", " NAME DELETED")
View 6 Replies
View Related
Apr 4, 2015
following is a working code
declare @dte as datetime='2015-04-01'
declare @StDt as Datetime = DATEADD(mm,DATEDIFF(mm,0,@dte), 0)
declare @EnDt as datetime = DATEADD( DD, -1, DATEADD(mm,DATEDIFF(mm,0,@dte) + 1, 0));
DECLARE @query AS NVARCHAR(MAX);
[code]...
iam getting the ouput correctly my requirement is i want to write a condition here
JOIN busdetails b ON m.bus_id = b.bus_id
i want to write this statement as
JOIN busdetails b ON m.bus_id = b.bus_id and m.uname='lekshmi'
when i tried this code iam getting error
View 1 Replies
View Related
Dec 19, 2007
I have a project that consists of a SQL db with an Access front end as the user interface. Here is the structure of the table on which this question is based:
Code Block
create table #IncomeAndExpenseData (
recordID nvarchar(5)NOT NULL,
itemID int NOT NULL,
itemvalue decimal(18, 2) NULL,
monthitemvalue decimal(18, 2) NULL
)
The itemvalue field is where the user enters his/her numbers via Access. There is an IncomeAndExpenseCodes table as well which holds item information, including the itemID and entry unit of measure. Some itemIDs have an entry unit of measure of $/mo, while others are entered in terms of $/yr, others in %/yr.
For itemvalues of itemIDs with entry units of measure that are not $/mo a stored procedure performs calculations which converts them into numbers that has a unit of measure of $/mo and updates IncomeAndExpenseData putting these numbers in the monthitemvalue field. This stored procedure is written to only calculate values for monthitemvalue fields which are null in order to avoid recalculating every single row in the table.
If the user edits the itemvalue field there is a trigger on IncomeAndExpenseData which sets the monthitemvalue to null so the stored procedure recalculates the monthitemvalue for the changed rows. However, it appears this trigger is also setting monthitemvalue to null after the stored procedure updates the IncomeAndExpenseData table with the recalculated monthitemvalues, thus wiping out the answers.
How do I write a trigger that sets the monthitemvalue to null only when the user edits the itemvalue field, not when the stored procedure puts the recalculated monthitemvalue into the IncomeAndExpenseData table?
View 4 Replies
View Related
Apr 4, 2015
Following is a working code
declare @dte as datetime='2015-04-01'
declare @StDt as Datetime = DATEADD(mm,DATEDIFF(mm,0,@dte), 0)
declare @EnDt as datetime = DATEADD( DD, -1, DATEADD(mm,DATEDIFF(mm,0,@dte) + 1, 0));
DECLARE @query AS NVARCHAR(MAX);
create table #bus_master(bus_id int,bus_name varchar(50),uname varchar(50))
insert into #bus_master values(100,'A','lekshmi')
[Code] ...
I am getting the output correctly. My requirement is i want to write a condition here
JOIN busdetails b ON m.bus_id = b.bus_id
I want to write this statement as
JOIN busdetails b ON m.bus_id = b.bus_id and m.uname='lekshmi'
When I tried this code I am getting error.
View 3 Replies
View Related
Sep 22, 2015
I am having 3 columns like A,B,C. In the C column I am having calculations like
=CInt(IIf(B=0,100,((A-B)/B)*100))
After this calculation if the column B is 0(zero) corresponding C column get display as "#Error", if B is not having 0 every thing is working fine.
In the calculation if I remove the " /B" it is working fine. So, how to display the value 100 in C if B=0.
View 5 Replies
View Related
Oct 17, 2015
I write a query to get some data as the following. but i need when a user check specified condition a query parameter change to specified condition :
create proc proc_ReservationDetails
(
@status nvarchar(50) = null
)
as
begin
select reservationId, reservationStatus, reservationDesc
[Code] .....
View 3 Replies
View Related
Oct 30, 2007
Hi...
I have data that i am getting through a dbf file. and i am dumping that data to a sql server... and then taking the data from the sql server after scrubing it i put it into the production database.. right my stored procedure handles a single plan only... but now there may be two or more plans together in the same sql server database which i need to scrub and then update that particular plan already exists or inserts if they dont...
this is my sproc...
ALTER PROCEDURE [dbo].[usp_Import_Plan]
@ClientId int,
@UserId int = NULL,
@HistoryId int,
@ShowStatus bit = 0-- Indicates whether status messages should be returned during the import.
AS
SET NOCOUNT ON
DECLARE
@Count int,
@Sproc varchar(50),
@Status varchar(200),
@TotalCount int
SET @Sproc = OBJECT_NAME(@@ProcId)
SET @Status = 'Updating plan information in Plan table.'
UPDATE
Statements..Plan
SET
PlanName = PlanName1,
Description = PlanName2
FROM
Statements..Plan cp
JOIN (
SELECT DISTINCT
PlanId,
PlanName1,
PlanName2
FROM
Census
) c
ON cp.CPlanId = c.PlanId
WHERE
cp.ClientId = @ClientId
AND
(
IsNull(cp.PlanName,'') <> IsNull(c.PlanName1,'')
OR
IsNull(cp.Description,'') <> IsNull(c.PlanName2,'')
)
SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Updated ' + Cast(@Count AS varchar(10)) + ' record(s) in ClientPlan.'
END
ELSE
BEGIN
SET @Status = 'No records were updated in Plan.'
END
SET @Status = 'Adding plan information to Plan table.'
INSERT INTO Statements..Plan (
ClientId,
ClientPlanId,
UserId,
PlanName,
Description
)
SELECT DISTINCT
@ClientId,
CPlanId,
@UserId,
PlanName1,
PlanName2
FROM
Census
WHERE
PlanId NOT IN (
SELECT DISTINCT
CPlanId
FROM
Statements..Plan
WHERE
ClientId = @ClientId
AND
ClientPlanId IS NOT NULL
)
SET @Count = @@ROWCOUNT
IF @Count > 0
BEGIN
SET @Status = 'Added ' + Cast(@Count AS varchar(10)) + ' record(s) to Plan.'
END
ELSE
BEGIN
SET @Status = 'No information was added Plan.'
END
SET NOCOUNT OFF
So how do i do multiple inserts and updates using this stored procedure...
Regards
Karen
View 5 Replies
View Related
Feb 28, 2006
Hello!
We just upgraded to SQL Server 2005 from SQL Server 2000. The DB was backed up using Enterprise Manager and restored with SQL Server Management Studio Express CTP. Everything went as expected (no errors, warnings, or any other indicator of problems).
The DB resides in a DB Server (Server1) and the application we are running is a Client/Server system where the AppServer resides on Server2.
During the application's operation all read, create, and delete transactions work fine but no update works. When viewing details in Trace Log I see this message after attempting any update:
Could not find server 'Server1' in sysservers. Execute sp_addlinkedserver to add the server to sysservers. (7202)
Any help is greatly appreciated,
Lucio Gayosso
View 19 Replies
View Related
May 10, 2006
Hi
I am developing a scientific application (demographic forecasting) and have a situation where I need to update a variety of rows, say the ith, jth and kth row that meets a particular condition, say, x.
I also need to adjust rows, say mth and nth that meet condition , say y.
My current solution is laborious and has to be coded for each condition and has been set up below (If you select this entire piece of code it will create 2 databases, each with a table initialised to change the 2nd,4th,8th and 16th rows, with the first database ignoring the condition and with the second applying the change only to rows with 'type1=1' as the condition.)
This is an adequate solution, but if I want to change the second row meeting a second condition, say 'type1=2', I would need to have another WITH...SELECT...INNER JOIN...UPDATE and I'm sure this would be inefficient.
Would there possibly be a way to introduce a rank by type into the table, something like this added column which increments for each type:
ID
Int1
Type1
Ideal Rank by Type
1
1
1
1
2
1
1
2
3
2
1
3
4
3
1
4
5
5
1
5
6
8
2
1
7
13
1
6
8
21
1
7
9
34
1
8
10
55
2
2
11
89
1
9
12
144
1
10
13
233
1
11
14
377
1
12
15
610
1
13
16
987
2
3
17
1597
1
14
18
2584
1
15
19
4181
1
16
20
6765
1
17
The solution would then be a simple update based on an innerjoin reflecting the condition and rank by type...
I hope this posting is clear, albeit long.
Thanks in advance
Greg
PS The code:
USE
master
GO
CREATE DATABASE CertainRowsToChange
GO
USE CertainRowsToChange
GO
CREATE TABLE InitialisedValues
(
InitialisedValuesID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL
)
GO
CREATE PROCEDURE Initialise
AS
BEGIN
INSERT INTO InitialisedValues (Int1 )
SELECT 2
INSERT INTO InitialisedValues (Int1 )
SELECT 4
INSERT INTO InitialisedValues (Int1 )
SELECT 8
INSERT INTO InitialisedValues (Int1 )
SELECT 16
END
GO
EXEC Initialise
/*=======================================================*/
CREATE TABLE AllRows
(
AllRowsID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL
)
GO
CREATE TABLE RowsToChange
(
RowsToChangeID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL
)
GO
CREATE PROCEDURE InitialiseRowsToChange
AS
BEGIN
INSERT INTO RowsToChange (Int1 )
SELECT 2
INSERT INTO RowsToChange (Int1 )
SELECT 4
INSERT INTO RowsToChange (Int1 )
SELECT 8
INSERT INTO RowsToChange (Int1 )
SELECT 16
END
GO
EXEC InitialiseRowsToChange
GO
CREATE PROCEDURE PopulateAllRows
AS
BEGIN
INSERT INTO AllRows (Int1 )
SELECT 1
INSERT INTO AllRows (Int1 )
SELECT 1
INSERT INTO AllRows (Int1 )
SELECT 2
INSERT INTO AllRows (Int1 )
SELECT 3
INSERT INTO AllRows (Int1 )
SELECT 5
INSERT INTO AllRows (Int1 )
SELECT 8
INSERT INTO AllRows (Int1 )
SELECT 13
INSERT INTO AllRows (Int1 )
SELECT 21
INSERT INTO AllRows (Int1 )
SELECT 34
INSERT INTO AllRows (Int1 )
SELECT 55
INSERT INTO AllRows (Int1 )
SELECT 89
INSERT INTO AllRows (Int1 )
SELECT 144
INSERT INTO AllRows (Int1 )
SELECT 233
INSERT INTO AllRows (Int1 )
SELECT 377
INSERT INTO AllRows (Int1 )
SELECT 610
INSERT INTO AllRows (Int1 )
SELECT 987
INSERT INTO AllRows (Int1 )
SELECT 1597
INSERT INTO AllRows (Int1 )
SELECT 2584
INSERT INTO AllRows (Int1 )
SELECT 4181
INSERT INTO AllRows (Int1 )
SELECT 6765
END
GO
EXEC PopulateAllRows
GO
SELECT * FROM AllRows
GO
WITH Temp(OrigID)
AS
(
SELECT OrigID FROM
(SELECT Row_Number() OVER (ORDER BY AllRowsID Asc ) AS RowScore, AllRowsID AS OrigID, Int1 AS OrigValue FROM Allrows) AS FromTable
INNER JOIN
RowsToChange AS ToTable
ON FromTable.RowScore = ToTable.Int1
)
UPDATE AllRows
SET Int1=1000
FROM
Temp as InTable
JOIN Allrows as OutTable
ON Intable.OrigID = OutTable.AllRowsID
GO
SELECT * FROM AllRows
GO
USE
master
GO
CREATE DATABASE ComplexCertainRowsToChange
GO
USE ComplexCertainRowsToChange
GO
CREATE TABLE InitialisedValues
(
InitialisedValuesID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL
)
GO
CREATE PROCEDURE Initialise
AS
BEGIN
INSERT INTO InitialisedValues (Int1 )
SELECT 2
INSERT INTO InitialisedValues (Int1 )
SELECT 4
INSERT INTO InitialisedValues (Int1 )
SELECT 8
INSERT INTO InitialisedValues (Int1 )
SELECT 16
END
GO
EXEC Initialise
/*=======================================================*/
CREATE TABLE AllRows
(
AllRowsID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL,
Type1 int NOT NULL
)
GO
CREATE TABLE RowsToChange
(
RowsToChangeID int identity(1 ,1) NOT NULL PRIMARY KEY,
Int1 int NOT NULL,
Type1 int NOT NULL
)
GO
CREATE PROCEDURE InitialiseRowsToChange
AS
BEGIN
INSERT INTO RowsToChange (Int1,Type1 )
SELECT 2, 1
INSERT INTO RowsToChange (Int1,Type1 )
SELECT 4, 1
INSERT INTO RowsToChange (Int1,Type1 )
SELECT 8, 1
INSERT INTO RowsToChange (Int1,Type1 )
SELECT 16, 1
END
GO
EXEC InitialiseRowsToChange
GO
CREATE PROCEDURE PopulateAllRows
AS
BEGIN
INSERT INTO AllRows (Int1, Type1 )
SELECT 1, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 1, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 2, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 3, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 5, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 8, 2
INSERT INTO AllRows (Int1, Type1 )
SELECT 13, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 21, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 34, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 55, 2
INSERT INTO AllRows (Int1, Type1 )
SELECT 89, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 144, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 233, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 377, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 610, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 987, 2
INSERT INTO AllRows (Int1, Type1 )
SELECT 1597, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 2584, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 4181, 1
INSERT INTO AllRows (Int1, Type1 )
SELECT 6765, 1
END
GO
EXEC PopulateAllRows
GO
SELECT * FROM AllRows
GO
WITH Temp(OrigID)
AS
(
SELECT OrigID FROM
(SELECT Row_Number() OVER (ORDER BY AllRowsID Asc ) AS RowScore, AllRowsID AS OrigID, Int1 AS OrigValue FROM Allrows WHERE Type1=1) AS FromTable
INNER JOIN
RowsToChange AS ToTable
ON FromTable.RowScore = ToTable.Int1
)
UPDATE AllRows
SET Int1=1000
FROM
Temp as InTable
JOIN Allrows as OutTable
ON Intable.OrigID = OutTable.AllRowsID
GO
SELECT * FROM AllRows
GO
View 3 Replies
View Related
Apr 18, 2007
Hello,
Although this SP intends to sorround a search text in double quotes, it seems that when called from Management Studio it throws a Syntax Error even before entering the SP.
createproc fts(@t nvarchar(1000)=null) as begin
select @t = '"' + @t + '"'
select @t
select * from dbo.products where CONTAINS(name, @t)
end
GO
exec fts @t = 'my product name'
GO
Msg 7630, Level 15, State 3, Procedure fts, Line 4
Syntax error near 'product' in the full-text search condition 'my product name'.
-------------------------
If I pass the string in double quotes I get a different error:
exec fts @t = '"my product name"'
Go
Msg 7630, Level 15, State 3, Procedure fts, Line 4
Syntax error near 'my' in the full-text search condition '""my product name""'.
Now, if I remove the quotes again and make the original call:
exec fts @t = 'my product name'
GO
-- Then it works fine.
Doing a :
dbcc freeproccache
GO
Shows the same behavior as outlined initially.
View 2 Replies
View Related
Feb 5, 2004
I have a web form that collects details on books (as an example), and in that form is a checkboxlist that displays an entry for each potential author in the database (as an example).
The user can obviously tick as many authors as they want to represent Authors of the book. The ticked entries form the entries in the BooksToAuthors table which only has BookID and AuthorID columns.
I have a number of questions:
How do I take what is in the CheckBoxList to the database and how does this relate to Stored Procedures?
Do I fill the checkbox selections into an Array? How do I get these 'many items' to a Stored Procedure that runs a transaction to put the book in and then the many rows in AuthorsToBooks.
What is being passed? Can you pass an array or something to a stored procedure?
View 4 Replies
View Related
Jun 19, 2007
As far as performance goes should I avoid using "IN" with update statements?Example:update table_nameset x = 5where y IN (select z from table_name1 where a = b and c = d)If this is terribly inefficient what are the alternatives?Thanks...
View 3 Replies
View Related
Sep 20, 2014
I have 3 queries and I need to see if there is a way to combine them since they do the same thing, or if there is a more efficient way I am missing. I run the query below on Table A to find the product first for TableA.Model=1, then for Model=2 and then Model=3. The reason I split it into three queries is I need Model=1 Customers only, then Model=2 only if there isn't a Model=1 Customer, etc.
UPDATE Table1 INNER JOIN TableA ON Table1.Product = TableA.Product SET Table1.Customer = [TableA].[Customer]
WHERE (((TableA.Model)="1") AND ((Table1.Customer) Is Null));
View 3 Replies
View Related
May 10, 2007
okay, so i have about 37 different updates i need to do to a table that is rather large (71million) and has no indexes. i know it's gunna table scan, and honestly, i'm not really worried about that. my question is, is there a way up squeeze all of these updates into one?
here is what i was going to do, but each one will take about an hour to run... (here are 5 of the 37 updates, but they are all basically the same concept)
update t1 set books_music='' from mailorder t1 where books_music is null
update t1 set Car_Buff='' from mailorder t1 where Car_Buff is null
update t1 set Childrens_Items_Buyers='' from mailorder t1 where Childrens_Items_Buyers is null
update t1 set Computer='' from mailorder t1 where Computer is null
update t1 set Crafts_Sewing='' from mailorder t1 where Crafts_Sewing is null
in FoxSlow (foxpro) i could just do something like this:
do while !eof()
replace books_music with '' for books_music=null
replace car_buff with '' for car_buff=null
skip
enddo
View 9 Replies
View Related
Feb 17, 2008
I have an SQL 2005 STD server, full install, that we use to run SQL and reporting services. When I run Microsoft Update, it shows updates for Visual Studio 2005 SP1 and MS Office 2003 SP3. The server does have MS Office 2003 web components installed, installed as part of the initial SQL server install, but not the MS Office suite software. It also has loaded the reporting services version of Visual studio 2005 that installs with reporting services, but not the entire version of Visual Studio 2005. Should I install these service pack updates? Is there any benifit?
View 3 Replies
View Related
Oct 29, 2007
Hi! I 'd like to update the database..I 'd like to update the same field, the first update would set all to 'No' and the second update woyuld set specific records to 'Yes':
1) "Update tblDept SET IsTop ='No'
2) "Update tblDept SET IsTop = 'Yes' WHERE id = 200 "
Cheers!
View 4 Replies
View Related
Mar 15, 2008
Hi, I just started learning ASP.NET this week and have watched a mountain of videos from this website which has helped me alot However I have been stuck on a problem for 2 days now. I have created an SQL database with the Following 2 tables: USERS COMPUTERSUserid Computerid firstname Useridsecondname Manufacturer Model I have made a relationship between the 2 tables. I then created a dataset with the following query:SELECT COMPUTERS.Computer_ID, COMPUTERS.Manufacturer, COMPUTERS.Model, USERS.First_Name, USERS.Last_Name FROM COMPUTERS INNER JOIN USERS ON COMPUTERS.User_ID = USERS.User_ID I however do not get the option in my grid view when i output this data, to UPDATE. The best i have found from google is that i need to use subqueries and not innerjoins but i just cant seem to get my head around them, please help as i feel my head may just explode if i think about this or try any more ways to get this to work :D
View 5 Replies
View Related
Dec 16, 2003
I am using MSDE Release A was wondering what is the best way to find out when there are critical updates for MSDE. Is there a notification service for MSDE like there is for Windows?
View 1 Replies
View Related
Jul 11, 2000
I'm pretty new to T-SQL and have an *easy* problem, for you experts, that I can't get seem to get solved. I'd like to loop through a list of items in TABLE "Items". I then want to use that list to loop through and SUM SALES and QTY for each item from a TABLE called "Shipments". As I loop through each item, I want to UPDATE the "Items" table with the Summary data. So, logically I'd do something like this:
SELECT item_no
FROM Items
BEGIN
SELECT SUM(sales) AS Total_Sales, SUM(qty) AS Total_Qty
WHERE item_no=@item_no
UPDATE Items
SET Sales=@Total_Sales,
Qty=@Total_Qty
WHERE item_no=@item_no
END
I've tried somewhat successfully to use cursors to create my loop query, but I cannot seem to get the SELECT and UPDATE correct in the loop itself. Can anyone steer me in the right direction (or better yet, provide a solution)?
Thanks for the help,
Chris
View 2 Replies
View Related
Jan 22, 2001
I have a number of columns with predefined character length but user can input more from gui. i want to trucncate automatically to the desired length and insert or update the database right now it does not allow me to update , or insert the values can i do it and how this is urgent
View 2 Replies
View Related
Sep 29, 2000
Hi
I am using SQL Server 6.5 as my backend for a VB6 Application.
This is a OLTP kind of package that I have developed with about 600 Users.
I use BeginTran and CommitTran between my Update/Insert Queries in my VB Application.
My database has grown considerably and all of a sudden, all
the CommitTran failed. None of the records were saved.
When I stopped and restarted my SQL Server, the operation became
normal all Update/Insert queries for the same Application succeeded.
(Note that I have not stopped my Server for the last 45 days).
WHY DOES THIS HAPPEN?
HOW DO I AVOID THIS IN FUTURE...
PLEASE HELP
Thanks
Jivee
View 1 Replies
View Related
Apr 5, 1999
Is there an easy way to update a Value field
for all records in One Table from a Value Field in another?
Both Tables have the same number of records.
View 3 Replies
View Related
Nov 6, 2006
How would I check a db to see if a record exists and if it does then do an update but if it doesn't do an insert. so: Set oRS = objDB.Execute("select loginid from computers where loginid='" & WshNetwork.Computername & WshNetwork.UserName & "'")
If that returns something then do an update but if not then do the insert.
View 2 Replies
View Related
Jun 18, 2004
Hi all,
I recently inherited multiple databases for a research study. These databases use an Access front end with the tables stored on SQL Server. Currently, there is a folder for each database on a network drive. I make changes to the front ends (forms, reports etc.) in a development version of the dbs, test them, have a user test them, and then import them to the production front end.
Each user has a copy of the front end on their 'C:' drive. The previous developer put together a separate VB app that copies the changed mdb files from the network drive to their 'C:' drive. This doesn't seem like the best solution to me but I haven't come up with a better one. I would appreciate any input.
Thanks,
Monk
View 1 Replies
View Related
Jun 23, 2004
I have two sql 2000 server tables one is active and one is terminated (I inherited this db) and I was thinking of having the active table automatically update the terminated table when an employee is terminated. Access is at the front end and in the form of the active table theres a drop down text box that has the employement status(active, terminated, on leave...etc) so when the status turns into terminated i want the acitve table to send those records to the terminated table, ( the data in both tables are not exactly the same). looking into a trigger or stored procedure. This is the first time I've done this so I'm doing some reasearch on how to handle it. Any suggestions
View 14 Replies
View Related
Jun 25, 2004
well as I get further into this project of automatic updates I'm fining more and more barriers. The combo list box which indicates whether the employee is terminated or active might be a problem with sql since you cant create a Row source and a Row source type in a sql table. that combo box exsist in the properties of the form. The Row Source Type is a Value List. Shoot :(
View 4 Replies
View Related
May 25, 2004
Hello,
I am working on a web app and am at a point where I have multiple rows in my GUI that need to be sent to and saved in SQL Server when the user presses Save. We want to pass the rows to a working table and the do a begin tran, move rows from working table to permanent tables with set processing, commit tran. The debate we are having is how to get the data to the work table. We can do individual inserts to the work table 1 round trip for each row (could be 100's of rows) or concatenate all rows into 1 long (up to 8K at a time) string and make one call sending the long string and then parse it into the work table in SQL Server. Trying to consider network usage and overhead by sending many short items vs 1 long item and cpu overhead for many inserts vs string manipulation and parsing. Suggestions?
Thanks you
Jeff
View 2 Replies
View Related
Jun 16, 2007
Hello guys,
I am askng for any help ...am trying to get this SQL language.
I want to provide an SQL query to set all the priority to 1 for all customers that have all their orders being for a product with importance of 100.
--------------------------------------------------------------------
There are three tables in the database: Customer, Product and Orders.
The Customer table has three column: Customer_id (PK), priority, Address.
The Orders table has three colums as well: Order_id (PK), Customer_id (FK), Product_id (FK)
The Product table has three columns as well: Product_id(PK), Product_name, Importance.
So the order table is connected to both the product and the customers table by respective foreign key.
View 2 Replies
View Related