Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Tuesday, March 27, 2012

Are Blank String and String with only Space characters equal to each other? They should not be!!

I have a table called Table_1

Table_1
--
a varchar(10),
b varchar(20)

and Column a is the Primary Key.

INSERT INTO Table_1
(a ,b)
VALUES
('' , 'BLANK STRING')

INSERT INTO Table_1
(a ,b)
VALUES
(' ' ,'4 SPACES')

When i execute this Insertions, it inserts the First Record but on the Second one it gives Violation of Uniqueness

(1 row(s) affected)
Msg 2627, Level 14, State 1, Line 9
Violation of PRIMARY KEY constraint 'PK_Table_1'. Cannot insert duplicate key in object 'dbo.Table_1'.
The statement has been terminated.

My Questions is that; HOW can a Blank String or a String with 4(or any number) space charcters in it can be EQUAL? In my opinion they should not be regarded as the same! Is there a solution to this issue? That's not the case in Oracle Database.

Thanks for your help!

Regards,
Cem

According to ANSI standards (or is it SQL Server's implementation of ANSI...), anyway, for sorting purposes, leading blanks are ignored. (And Primary Keys are 'sorted'...)

Try these two statements, the first will provide the 'right' answer, and the second will provide the 'real' answer.


SELECT len( (replicate( ' ', 4 )) )
SELECT datalength( (replicate( ' ', 4 )) )

|||

You should check the setting of SET ANSI_PADDING. If you want behavior such as you find in ORACLE, you will need SET ANSI_PADDING ON. That way trailing blanks will not be trimmed from your VARCHAR insert statements.

http://msdn2.microsoft.com/en-us/library/ms187403.aspx

Dan

Tuesday, March 20, 2012

applying sum or count funtions to a group

How can I make reporting services to calculate the sum of a value that is
displayed in a group? When I insert the funtion =Sum(Fields!nuAmount.Value)
in the footer of a group, I get the sum considering all values included in a
detail. I only want the sum to be calculated from the group header values
diaplyeddid you get any answer on this quest?
reg.
Kjell Brandes
"FedericAguirre" <FedericAguirre@.discussions.microsoft.com> wrote in message
news:C518AE1F-FFE3-4F16-A007-165420532AB1@.microsoft.com...
> How can I make reporting services to calculate the sum of a value that is
> displayed in a group? When I insert the funtion
=Sum(Fields!nuAmount.Value)
> in the footer of a group, I get the sum considering all values included in
a
> detail. I only want the sum to be calculated from the group header values
> diaplyed|||do some of the calculations on the query side. If you want a count of orders
group by order# then do a count of them on the report.
"FedericAguirre" wrote:
> How can I make reporting services to calculate the sum of a value that is
> displayed in a group? When I insert the funtion =Sum(Fields!nuAmount.Value)
> in the footer of a group, I get the sum considering all values included in a
> detail. I only want the sum to be calculated from the group header values
> diaplyed

Sunday, March 11, 2012

Apply insert duplicated key record

Hi~
When insert, just insert if it is a new item or update it if duplicated. The update operation should be summing or averaging. Anyone help?

INSTEAD OF INSERT Trigger
-Check for dupe
--If dupe, increment
--Else INSERT

Adamus

|||

Thank you for reply.

But would you give me some sample query?

|||

1. Validate if the data availabile in the Table

2. If Yes , execute the Update command

3. If No, execute the Insert command

(ex)

if Exists (Select * From SomeTable Where SomeColumn=SomeValue)

Update

Set

SomeValueColumn = SomeValueColumn + New Value

Where

SomeColumn=SomeValue

Else

Insert Into SomeTable values (...)

|||

Thank you for your help.
Here is more specific case.

CREATE TABLE mytable
(
id1 int,
id2 int,
value1 int,
PRIMARY KEY(id1,id2)
);

CREATE TRIGGER mytrigger ON mytable
INSTEAD OF INSERT
AS
BEGIN
IF EXISTS(SELECT * FROM INSERTED I,mytable M
WHERE I.id1=M.id1 AND I.id2=M.id2)
UPDATE mytable SET value1 = value1 + 100
ELSE
INSERT INTO mytable SELECT id1,id2,value1 FROM INSERTED
END

BULK INSERT mytable FROM 'mydatafile_1.dat' WITH (FIRE_TRIGGERS);(1)
BULK INSERT mytable FROM 'mydatafile_2.dat' WITH (FIRE_TRIGGERS);(2)
BULK INSERT mytable FROM 'mydatafile_3.dat' WITH (FIRE_TRIGGERS);(3)

I want insert a record if new item, update it by adding new item value to the original value.

Suppose the 'mydatafile_1.dat' has all new items(1).
'mydatafile_2.dat' has some new items and some duplicated items(2)
and 'mydatafile_3.dat' has all new items(3).

Only (1) and (3) are applied correctly. (2) is updated all of record but never inserted the new items.
It seems that the validation part should be repaired.
And, I want to change 100 to the new inserted value.

Wednesday, March 7, 2012

Application Roles and Bulk Insert

Is it possible to grant a user access to Bulk Insert via an Application Role
?
I have a situation where I dont want to grant users direct access to any
tables, but there is one table that they will need to do a bulk insert into.
I cant see anywhere that you can assign an approle as part of bulkadmin.
Any ideas of how to do this would be appreciated. Thanks.I don't believe you can use "Application roles" for this, but you can assign
"Bulk Insert Administrator" Server Role to any individual Server Login...
Under SQL Server Login Properties, Server Roles, one of the Server Roles is
Bulk insert Administrator.
"Jace" wrote:

> Is it possible to grant a user access to Bulk Insert via an Application Ro
le?
> I have a situation where I dont want to grant users direct access to any
> tables, but there is one table that they will need to do a bulk insert int
o.
> I cant see anywhere that you can assign an approle as part of bulkadmin.
> Any ideas of how to do this would be appreciated. Thanks.

Saturday, February 25, 2012

Application insert\update\delete

Hi,
How can i know how many insert\update\delete done by application daily
in sql server 2000 in particaular database
is there any cmd to check the same in sql server 2000
Regards
AbhinavSeveral options:
1) Get a copy of ApexSQL Log and use it for auditing.
2) Purchase an auditing package (or write your own) using triggers to log
that an update/insert/delete was performed. You will not be able to
actually know the exact statement this way.
3) Modify the application code to log these statements prior to or just
after executing them.
4) Write a network packet interogator and disassemble all sql server bound
packets and check for appropriate statements and log them.
Some of these are easier and more efficient than others!! :-))
--
TheSQLGuru
President
Indicium Resources, Inc.
"Abhi" <bawejaji@.gmail.com> wrote in message
news:1188302835.786870.105940@.r23g2000prd.googlegroups.com...
> Hi,
> How can i know how many insert\update\delete done by application daily
> in sql server 2000 in particaular database
> is there any cmd to check the same in sql server 2000
> Regards
> Abhinav
>

Sunday, February 19, 2012

append xml nodes

I'm searching for a way to insert nodes from an xml document into an other.
My solution to the problem is something like this:
ALTER PROCEDURE [dbo].[insertOrder]
@.Customer xml (dbo.schemaCustomer),
@.Product xml (dbo.schemaProduct)
AS
BEGIN
declare @.app varchar(1024)
declare @.x xml
set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
'</Product>'+ CAST(@.Customer as varchar(1024)) +
'<id_order>0</id_order></Order>'
insert into xOrder (doc) values (@.app)
END
but I think there's a better way to solve the problem.
Is it possible to do this witout any casting operation?
Thank you, Luca.Hello luca,

> I'm searching for a way to insert nodes from an xml document into an
> other. My solution to the problem is something like this:
> ALTER PROCEDURE [dbo].[insertOrder]
> @.Customer xml (dbo.schemaCustomer),
> @.Product xml (dbo.schemaProduct)
> AS
> BEGIN
> declare @.app varchar(1024)
> declare @.x xml
> set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
> '</Product>'+ CAST(@.Customer as varchar(1024)) +
> '<id_order>0</id_order></Order>'
> insert into xOrder (doc) values (@.app)
> END
> but I think there's a better way to solve the problem. Is it possible
> to do this witout any casting operation? Thank you, Luca.
Not that I've found. Something like this would be ideal if doc was XML-typed
as X1 is here:
declare @.x1 xml,@.x2 xml
set @.x1 = '<pet id="1" ownerID="1"><name>Jack</name></pet>'
set @.x2 = '<descr>Grey<descr>'
set @.x1.modify('insert sql:variable("@.x2") into /pet[1]')
However, the modify method won't work with XML-type variables. Nor does trea
ting
@.x2 as a varchar(x) really get you any place since when you do try that,
you get:
XQuery [modify()]: Only non-document nodes can be inserted. Found "xs:string
?".
.modify() also requires the use of string literal as the query. So, Ick.
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/|||Try:
CREATE TABLE xOrder(doc xml)
go
CREATE PROCEDURE [dbo].[insertOrder]
@.Customer xml, --(dbo.schemaCustomer),
@.Product xml --(dbo.schemaProduct)
AS
BEGIN
insert into xOrder (doc) select (
select @.Customer, @.Product as "Product", 0 as "id_order"
FOR XML PATH('Order'), TYPE
)
END
go
exec insertOrder '<a/>', '<b/>'
select * from xOrder
Best regards
Michael
"luca" <luca@.discussions.microsoft.com> wrote in message
news:1F06F5E3-E9C9-4B40-ACFE-2784345D1F40@.microsoft.com...
> I'm searching for a way to insert nodes from an xml document into an
> other.
> My solution to the problem is something like this:
> ALTER PROCEDURE [dbo].[insertOrder]
> @.Customer xml (dbo.schemaCustomer),
> @.Product xml (dbo.schemaProduct)
> AS
> BEGIN
> declare @.app varchar(1024)
> declare @.x xml
> set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
> '</Product>'+ CAST(@.Customer as varchar(1024)) +
> '<id_order>0</id_order></Order>'
> insert into xOrder (doc) values (@.app)
>
> END
> but I think there's a better way to solve the problem.
> Is it possible to do this witout any casting operation?
> Thank you, Luca.
>

append xml nodes

I'm searching for a way to insert nodes from an xml document into an other.
My solution to the problem is something like this:
ALTER PROCEDURE [dbo].[insertOrder]
@.Customer xml (dbo.schemaCustomer),
@.Product xml (dbo.schemaProduct)
AS
BEGIN
declare @.app varchar(1024)
declare @.x xml
set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
'</Product>'+ CAST(@.Customer as varchar(1024)) +
'<id_order>0</id_order></Order>'
insert into xOrder (doc) values (@.app)
END
but I think there's a better way to solve the problem.
Is it possible to do this witout any casting operation?
Thank you, Luca.
Hello luca,

> I'm searching for a way to insert nodes from an xml document into an
> other. My solution to the problem is something like this:
> ALTER PROCEDURE [dbo].[insertOrder]
> @.Customer xml (dbo.schemaCustomer),
> @.Product xml (dbo.schemaProduct)
> AS
> BEGIN
> declare @.app varchar(1024)
> declare @.x xml
> set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
> '</Product>'+ CAST(@.Customer as varchar(1024)) +
> '<id_order>0</id_order></Order>'
> insert into xOrder (doc) values (@.app)
> END
> but I think there's a better way to solve the problem. Is it possible
> to do this witout any casting operation? Thank you, Luca.
Not that I've found. Something like this would be ideal if doc was XML-typed
as X1 is here:
declare @.x1 xml,@.x2 xml
set @.x1 = '<pet id="1" ownerID="1"><name>Jack</name></pet>'
set @.x2 = '<descr>Grey<descr>'
set @.x1.modify('insert sql:variable("@.x2") into /pet[1]')
However, the modify method won't work with XML-type variables. Nor does treating
@.x2 as a varchar(x) really get you any place since when you do try that,
you get:
XQuery [modify()]: Only non-document nodes can be inserted. Found "xs:string
?".
..modify() also requires the use of string literal as the query. So, Ick.
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/
|||Try:
CREATE TABLE xOrder(doc xml)
go
CREATE PROCEDURE [dbo].[insertOrder]
@.Customer xml, --(dbo.schemaCustomer),
@.Product xml --(dbo.schemaProduct)
AS
BEGIN
insert into xOrder (doc) select (
select @.Customer, @.Product as "Product", 0 as "id_order"
FOR XML PATH('Order'), TYPE
)
END
go
exec insertOrder '<a/>', '<b/>'
select * from xOrder
Best regards
Michael
"luca" <luca@.discussions.microsoft.com> wrote in message
news:1F06F5E3-E9C9-4B40-ACFE-2784345D1F40@.microsoft.com...
> I'm searching for a way to insert nodes from an xml document into an
> other.
> My solution to the problem is something like this:
> ALTER PROCEDURE [dbo].[insertOrder]
> @.Customer xml (dbo.schemaCustomer),
> @.Product xml (dbo.schemaProduct)
> AS
> BEGIN
> declare @.app varchar(1024)
> declare @.x xml
> set @.app = '<Order><Product>' + CAST(@.Product as varchar(1024)) +
> '</Product>'+ CAST(@.Customer as varchar(1024)) +
> '<id_order>0</id_order></Order>'
> insert into xOrder (doc) values (@.app)
>
> END
> but I think there's a better way to solve the problem.
> Is it possible to do this witout any casting operation?
> Thank you, Luca.
>

Thursday, February 16, 2012

Append one Table one with Table Two

Hello everyone I am trying to append data from one table to another, but SQL wont let me it says that I cannot insert null values.[main table] and [Report] Now one table has more records then the other, I ran a query and found in the report table about 903 records more then the [main table]. Anyone know what I should do the data types are the same for the primary key. I just need to insert some fields from the Main Table to the Report tbl. Can anyone help please?

Code Snippet

INSERT INTO dbo.Report
(Area, LossType, Loss,)
SELECT dbo.Report.Area, dbo.Report.LossType, dbo.Report.Loss, dbo.[Main Table].[IR Number]
FROM dbo.[Main Table] INNER JOIN
dbo.Report ON dbo.[Main Table].[IR Number] = dbo.Report.[Incident Report No]

Code Snippet

SELECT dbo.[Main Table].[IR Number], dbo.Report.[Incident Report No], dbo.Report.LossType, dbo.Report.Loss, dbo.Report.Area
FROM dbo.[Main Table] INNER JOIN
dbo.Report ON dbo.[Main Table].[IR Number] = dbo.Report.[Incident Report No]

There is not quite enough information to give you a defenitive response, but here are some ideas. (The TABLE definintions are sorely needed in this situation.)

In the report table, there are constraints on some columns that prohibit records from having NULL values. Some of the records from the SELECT query have NULL values and cannot be added to the report table. Remove the NULL value constraints from the Report table OR explore why the query is providing data with NULL values and correct the query.

It would help us better assist you if you could include table DDL, query strategy used so far, sample data in the form of INSERT statements, and an illustration of the desired results. (For help with that refer to: http://www.aspfaq.com/5006 and to http://classicasp.aspfaq.com/general/how-do-i-make-sure-my-asp-question-gets-answered.html )

The less 'set up' work we have to do, the more likely you are going to have folks tackle your problem and help you. Without this effort from you, we are just playing guessing games.

|||

Sorry about that thank you Arnie I will try to remember to do that. is this ok?


Code Snippet

CREATE TABLE [IncidentReports] (
[Notes] [nvarchar] (4000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_IncidentReports_Notes] DEFAULT (N'Scanned Report'),
[I/RDocument] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_IncidentReports_I/RDocument] DEFAULT (N'Scanned Reports'),
[Action Type] [int] NULL ,
[Action] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Guest] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Employee] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Loss Type] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Loss] [money] NULL CONSTRAINT [DF_IncidentReports_Loss] DEFAULT (0.00),
[Violation Type] [int] NULL ,
[Violation] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Inspector] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Area] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Date] [datetime] NULL ,
[IR Number] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
CONSTRAINT [PK_IncidentReports] PRIMARY KEY CLUSTERED
(
[IR Number]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Code Snippet

CREATE TABLE [Main Table] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[IR Number] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Date] [datetime] NULL ,
[Inspector] [int] NULL ,
[Area] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Violation] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Violation Type] [int] NULL ,
[Loss] [money] NULL ,
[Loss Type] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Employee] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Guest] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Action] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Action Type] [int] NULL ,
[Notes] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
CONSTRAINT [PK_Main Table] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO


|||

Thank you, that really helps to see what we are working with.

I noticed that in [Main Table], [IR Number] can be NULL, while in [IncidentReports], [IR Number] is NOT NULL.

Could there be NULL values in the [Main Table] for [IR Number]?

If so, attempting to add those record to the reporting table will fail due to the NOT NULL constraint.

|||Ok I fixed that and tried to insert again but it's still giving me that message "Cannot insert the value Null into column 'Incident Report No', table 'incident reportsdb.dbo.Report_Tbl'; column does not allwo nulls. INSERT fails|||

Now back to your original query:

INSERT INTO dbo.Report
(Area, LossType, Loss,)
SELECT dbo.Report.Area, dbo.Report.LossType, dbo.Report.Loss, dbo.[Main Table].[IR Number]
FROM dbo.[Main Table] INNER JOIN
dbo.Report ON dbo.[Main Table].[IR Number] = dbo.Report.[Incident Report No]

It appears that there is something now quite right with the SELECT query. Follow me as I try to tease it out.

You are inserting into three (3) columns, but your SELECT query produces four(4) columns. Therefore, you are inadvertently attempting to insert a NULL value into [Incident Report No]. I also question the purpose of the JOIN between [Reports] and [Main Table]. As a result, you are attempting to insert other columns that may have NULL values (Report.Area, Report.LossType, Report.Loss.

It seems to me that you would want to be SELECTing the data from [Main Table] to insert into the Reporting table. Let me know if I am anywhere in the ballpark...


Code Snippet


INSERT INTO dbo.IncidentReports
( [IR Number],
Area,
LossType,
Loss
)
SELECT
dbo.[Main Table].[IR Number]
dbo.[Main Table].Area,
dbo.[Main Table].LossType,
dbo.[Main Table].Loss
FROM dbo.[Main Table]
WHERE {criteria}

|||

Heres my statement I tried before that one and I'm still getting that message...[banging head against wall] Thank you so much Arnie for helping me I really appreciate it Smile

Code Snippet

INSERT INTO dbo.Report
(LossType, Loss, Area)
SELECT [Loss Type], Loss, Area
FROM dbo.[Main Table]

|||

The [IncidentReports] table definition requires a value for [IR Number].

[IR Number] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,

You MUST include a value for [IR Number]. (Or change the table definition for [IncidentReports] and not require it.)

Did the previous query suggestion I offered, that included .[Main Table].[IR Number] not work for you?

|||

this what your talking about

Code Snippet

INSERT INTO dbo.Report
( [Incident Report No],
Area,
LossType,
Loss
)
SELECT
dbo.[Main Table].[IR Number]
dbo.[Main Table].Area,
dbo.[Main Table].LossType,
dbo.[Main Table].Loss
FROM dbo.[Main Table]
WHERE [Incident Report No] = [IR NUMBER]

RETURN

|||

Yes. But I did have a typo and you must have caught this before I corrected the typo.

[Incident Report No] should be [IR Number]

Make that change and see if the query executes and gives you the data you want.

|||

Oh shoot sorry Arnie I did a DDL on the wrong table too

Code Snippet

CREATE TABLE [Report] (
[Incident Report No] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date] [datetime] NULL ,
[Time] [datetime] NULL ,
[Investigators Name] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Reported by] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Law Enforcement Agency] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Name of Officer] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Evidence Seized] [nvarchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Associated Reports] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Corrective Action] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Report_Corrective Action] DEFAULT (N'YES'),
[Comments] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[I/RDocument] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Report_I/RDocument] DEFAULT (N'SCANNED REPORT'),
[TypeOfIncident] [nvarchar] (300) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Exclusion] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Report_Exclusion] DEFAULT (N'NO'),
[86_D] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Report_86_D] DEFAULT (N'NO'),
[Loss] [money] NULL CONSTRAINT [DF_Report_Loss] DEFAULT (0.0000),
[LossType] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Area] [nvarchar] (75) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Action/Incident] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Security/GC] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Report_Security/GC] DEFAULT (N'GC'),
CONSTRAINT [PK_Report] PRIMARY KEY CLUSTERED
(
[Incident Report No]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

|||

Then change the query to [Incident Report No] on the INSERT portion -NOT the SELECT.

Code Snippet

INSERT INTO dbo.Report
( [Incident Report No],
Area,
LossType,
Loss
)
SELECT
dbo.[Main Table].[IR Number]
dbo.[Main Table].Area,
dbo.[Main Table].LossType,
dbo.[Main Table].Loss
FROM dbo.[Main Table]
WHERE {criteria}

|||

Is this part correct though

WHERE [Incident Report No] = [IR Number]

See I have a database that I created a while ago and I found the script I used finally and I used a SP_Procedure to do that

Code Snippet

CREATE PROCEDURE [InsertTerms]
AS
INSERT INTO [GamingCommissiondb].[dbo].[TERMINATION] ( [TM #],
[FirstName],
[LastName],
[SocialSecurityNumber],
[DateHired],
[Status],
[Title],
[DepartmentName])

SELECT a.TM#, a.FirstName, a.LASTNAME, a.SSN#, a.HIREDATE, a.STATUS, a.JOBTITLE, a.DEPT#
FROM EmployeeGamingLicense AS a
WHERE a.STATUS = 'TERMINATED'
RETURN
GO

|||

I don't think that you want

[Incident Report No] = [IR Number]

as a WHERE clause. First, since there is not a JOIN between the two tables, it would fail; second, there is not a column named [Incident Report No] in the [Main Table] table; and last, if there was a JOIN between [Main Table] and [Report], you would only get data that already exists in [Report], and it would not add any NEW data.

Turning the INSERT query into a stored procedure is fine. (Remove the WHERE {criteria} IF you want all rows from [Main Table], otherwise, add the appropriate filter.)

Code Snippet


CREATE PROCEDURE dbo.InsertReportData
AS
INSERT INTO dbo.Report
( [Incident Report No],
Area,
LossType,
Loss
)
SELECT
dbo.[Main Table].[IR Number]
dbo.[Main Table].Area,
dbo.[Main Table].LossType,
dbo.[Main Table].Loss
FROM dbo.[Main Table]
WHERE {criteria}

|||

Thank you so much for your help Arnie YOUR THE BEST

I'm still learning SQL, just gotta keep reading and trying

Append a field

Hello,

How do I append data on an update?
I have a table with a field that is nVarchar(1000) and the initial insert is a few sentences. If I wanted to add to that row using an update statement and without starting at the end of the sentences, how would I write that?

Update table set fieldname = 'more data' where value = @.variable

instead of

Update table set fieldname = 'initial data more data' where value = @.variable

and the 'more data' appends to the initial data... hmmm

help please.I'm not exactly following you. If you want to do both an INSERT and an UPDATE you need 2 different commands.


INSERT INTO table (ID, fieldname) VALUES(@.MyID, 'initial data')
UPDATE table SET fieldname = fieldname + ' more data' WHERE ID = @.MyID

Maybe you could explain further?

Terri|||OK, lets see...

An existing field containing data:

'A small red dog crapped on my lawn.'

In a textbox append to that same field:

'Then the owner cleaned it up.'

So now the field will contain:
'A small red dog crapped on my lawn. Then the owner cleaned it up.'

If i perform the statement like this:
Inset Into table (fieldname) Values ('Then the owner cleaned it up.') where value = @.value

Won't the 'A small red dog crapped on my lawn.' part be overwritten?|||No, you'd get an error ;-) You can't put a WHERE on an INSERT. What you need is an UPDATE:


UPDATE table SET fieldname = RTRIM(fieldname) + 'Then the owner cleaned it up.' WHERE value = @.value

(Note that you'd only need the RTRIM if the datatype of that field is char. Varchar data will not have extra spaces padding it out to the field length.

Terri

Append / Insert Into Question

When appending data from one table to another...
If the structure is the same,
do you need to list all fields in the query
insert into t1 ( f1, f2, f3 etc..)
Select f1, f2, f3 etc from t2
Thanks in advance,
Bob.John 3:16 wrote:
> When appending data from one table to another...
> If the structure is the same,
> do you need to list all fields in the query
> insert into t1 ( f1, f2, f3 etc..)
> Select f1, f2, f3 etc from t2
> Thanks in advance,
> Bob.
Actually you don't have to but it's silly not to. It is valid syntax to
leave out the column list in an INSERT but if you do that SQL will
match the target columns by their relative positions, not by name. Your
code may be less reliable and certainly harder to maintain and support
if you don't reference columns by name. The wisest policy is to list
the column names every time.
You can save yourself some typing by dragging the column lists from the
Object Browser in Query Analyzer.
David Portas
SQL Server MVP
--|||Works for me:
insert t1 select * from t2
"John 3:16" <bobmcc@.tricoequipment.com> wrote in message
news:OQUh2Jq9FHA.1844@.TK2MSFTNGP11.phx.gbl...
> When appending data from one table to another...
> If the structure is the same,
> do you need to list all fields in the query
> insert into t1 ( f1, f2, f3 etc..)
> Select f1, f2, f3 etc from t2
> Thanks in advance,
> Bob.
>|||Nope - but it's good practice at any time.
For a shortcut to get started, in Query Analyzer's Object Browser, you
can right-click \ Script object to [desired target] As \ Insert.
John 3:16 wrote:
> When appending data from one table to another...
> If the structure is the same,
> do you need to list all fields in the query
> insert into t1 ( f1, f2, f3 etc..)
> Select f1, f2, f3 etc from t2
> Thanks in advance,
> Bob.
>|||...one other thing.
This is maybe a good idea for a one time thing.
I would not use this method in production code.
"John 3:16" <bobmcc@.tricoequipment.com> wrote in message
news:OQUh2Jq9FHA.1844@.TK2MSFTNGP11.phx.gbl...
> When appending data from one table to another...
> If the structure is the same,
> do you need to list all fields in the query
> insert into t1 ( f1, f2, f3 etc..)
> Select f1, f2, f3 etc from t2
> Thanks in advance,
> Bob.
>|||Thanks David.
..Like you said, the time savings doesn't justify
future potential problems resulting from source or target changes.
Thanks for the reply,
Bob.

> Actually you don't have to but it's silly not to. It is valid syntax to
> leave out the column list in an INSERT but if you do that SQL will
> match the target columns by their relative positions, not by name. Your
> code may be less reliable and certainly harder to maintain and support
> if you don't reference columns by name. The wisest policy is to list
> the column names every time.
> You can save yourself some typing by dragging the column lists from the
> Object Browser in Query Analyzer.
> --
> David Portas
> SQL Server MVP
> --
>|||Thanks Raymond
"Raymond D'Anjou" <rdanjou@.canatradeNOSPAM.com> wrote in message
news:%23gnyFTq9FHA.472@.TK2MSFTNGP15.phx.gbl...
> ...one other thing.
> This is maybe a good idea for a one time thing.
> I would not use this method in production code.
> "John 3:16" <bobmcc@.tricoequipment.com> wrote in message
> news:OQUh2Jq9FHA.1844@.TK2MSFTNGP11.phx.gbl...
>|||Thanks Trey.
"Trey Walpole" <treypole@.newsgroups.nospam> wrote in message
news:eEBw2Sq9FHA.3132@.TK2MSFTNGP12.phx.gbl...
> Nope - but it's good practice at any time.
> For a shortcut to get started, in Query Analyzer's Object Browser, you can
> right-click \ Script object to [desired target] As \ Insert.
>
> John 3:16 wrote:

Monday, February 13, 2012

Apostrophe in char and varchar columns

HI all,
When trying to insert text into a char or varchar column that contains an
apostrophe ' I get an error message
"the value you entered is not consistant with the datatype or length of the
colum"
I know the length is not a problem, and I'm sure that ' is a char value.
How do I deal with this.
I need to import text type date, not long less thatn 100 char, from anothe
database into an sql table
Thanks
RobertOk figured it out. Makes perfect sense
Thanks
"Robert Bravery" <me@.u.com> wrote in message
news:eBAeJKrLGHA.536@.TK2MSFTNGP09.phx.gbl...
> HI all,
> When trying to insert text into a char or varchar column that contains an
> apostrophe ' I get an error message
> "the value you entered is not consistant with the datatype or length of
the
> colum"
> I know the length is not a problem, and I'm sure that ' is a char value.
> How do I deal with this.
> I need to import text type date, not long less thatn 100 char, from anothe
> database into an sql table
> Thanks
> Robert
>

Sunday, February 12, 2012

anything wrong with this trigger?

Hello,
I'm trying to create a trigger that will log to the eventviewer whenever
there is an update, delete, or insert statement made to the employee table.
However, I'm UNABLE to run any INSERT or DELETE statement into the employee
table when I have the severity level from 10-16 from the RAISERROR function.
I can run update just fine with the same severity level. Any idea what could
be causing this?
Thx
CREATE TRIGGER dbo.Audit ON dbo.Employee
FOR UPDATE, INSERT, DELETE
AS
BEGIN
DECLARE @.@.USERNAME varchar(30)
SET @.@.USERNAME = CURRENT_USER
RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
with log
END
I don't think RAISERROR is the right function for your requirements.
Consider using xp_logevent. More info on this at:
http://msdn.microsoft.com/library/de...aa-sz_6dmc.asp
With RAISERROR, you are unnecessarily raising an error for no apparent
reason. All you wanted was to log that an insert/update/delete occured.
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>
|||I would also suggest changing the name of your local variable from
@.@.username ( which implies global, but is not) to @.username...
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>

anything wrong with this trigger?

Hello,
I'm trying to create a trigger that will log to the eventviewer whenever
there is an update, delete, or insert statement made to the employee table.
However, I'm UNABLE to run any INSERT or DELETE statement into the employee
table when I have the severity level from 10-16 from the RAISERROR function.
I can run update just fine with the same severity level. Any idea what could
be causing this?
Thx
CREATE TRIGGER dbo.Audit ON dbo.Employee
FOR UPDATE, INSERT, DELETE
AS
BEGIN
DECLARE @.@.USERNAME varchar(30)
SET @.@.USERNAME = CURRENT_USER
RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
with log
ENDI don't think RAISERROR is the right function for your requirements.
Consider using xp_logevent. More info on this at:
http://msdn.microsoft.com/library/d.../>
sz_6dmc.asp
With RAISERROR, you are unnecessarily raising an error for no apparent
reason. All you wanted was to log that an insert/update/delete occured.
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>|||I would also suggest changing the name of your local variable from
@.@.username ( which implies global, but is not) to @.username...
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>

anything wrong with this trigger?

Hello,
I'm trying to create a trigger that will log to the eventviewer whenever
there is an update, delete, or insert statement made to the employee table.
However, I'm UNABLE to run any INSERT or DELETE statement into the employee
table when I have the severity level from 10-16 from the RAISERROR function.
I can run update just fine with the same severity level. Any idea what could
be causing this?
Thx
CREATE TRIGGER dbo.Audit ON dbo.Employee
FOR UPDATE, INSERT, DELETE
AS
BEGIN
DECLARE @.@.USERNAME varchar(30)
SET @.@.USERNAME = CURRENT_USER
RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
with log
ENDI don't think RAISERROR is the right function for your requirements.
Consider using xp_logevent. More info on this at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_xp_aa-sz_6dmc.asp
With RAISERROR, you are unnecessarily raising an error for no apparent
reason. All you wanted was to log that an insert/update/delete occured.
--
Vyas, MVP (SQL Server)
http://vyaskn.tripod.com/
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>|||I would also suggest changing the name of your local variable from
@.@.username ( which implies global, but is not) to @.username...
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Richard" <richardtran@.hotmail.com> wrote in message
news:OsSW3tGZEHA.3420@.TK2MSFTNGP12.phx.gbl...
> Hello,
>
> I'm trying to create a trigger that will log to the eventviewer whenever
> there is an update, delete, or insert statement made to the employee
table.
> However, I'm UNABLE to run any INSERT or DELETE statement into the
employee
> table when I have the severity level from 10-16 from the RAISERROR
function.
> I can run update just fine with the same severity level. Any idea what
could
> be causing this?
>
> Thx
>
> CREATE TRIGGER dbo.Audit ON dbo.Employee
> FOR UPDATE, INSERT, DELETE
> AS
> BEGIN
> DECLARE @.@.USERNAME varchar(30)
> SET @.@.USERNAME = CURRENT_USER
> RAISERROR ('Employee table has been updated by: %s', 15, 1, @.@.USERNAME)
> with log
> END
>