Get the wrong line ID in ms sql - sql

I have an INSERT statment wich inserts large amount of data into tableA from tableB.
Here is a very simple code example:
INSERT [dbo].[tableA]
SELECT field1 [field_1]
FROM [dbo].[tableB]
WHERE [codeID] IN (SELECT [codeID] FROM #tempTable WHERE RecordMarker = 1)
There is a temporary table wich holds codeIDs (at least 1 or more) needed to insert to tableA.
But there would be incorrent data in tableB what cannot be inserted into tableA. For example an numberic(30,2) field cannot map to numeric(13,2). In this case I get an excetpion and the statement has been terminated.
How can I get the CodeID or the wrong line number in tableB if I get an error? Now I have just the error message but no line number.
For example:
Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting numeric to data type numeric.
The statement has been terminated.
EDIT: There are more than one field in the table with different field types. So the numeric type is just an example.

Please try the following:
INSERT [dbo].[tableA]
SELECT field1 [field_1]
FROM [dbo].[tableB]
WHERE [codeID] IN (SELECT [codeID] FROM #tempTable WHERE RecordMarker = 1)
AND [codeID] <= 9999999999999.99;
INSERT ErrorLog
SELECT *
FROM [dbo].[tableB]
WHERE [codeID] > 9999999999999.99;

If you know the type of the destination field you're having the issue with, in this case a numeric of (13,2) precision, you can run a SELECT with a TRY_CONVERT on the potential problem field against your temp table and filter for NULL results. You could add a WHERE clause to your insert statement if you wanted to ensure that it would run successfully and not try to insert those "bad" rows.
CREATE TABLE #t (x NUMERIC(30,2),field2 varchar(10))
INSERT INTO #t
SELECT 123456789.23,'x'
UNION
SELECT 12345678901212343.23,'y'
UNION
SELECT 12345678923523523235.23,'z'
UNION
SELECT 42.0, 'a'
SELECT *, TRY_CONVERT(NUMERIC(13,2),x,1) [Converted to numeric(13,2)] FROM #t
Reference: http://msdn.microsoft.com/en-us/library/hh230993.aspx

Related

SQL HELP INSERT statments contain more items than the insert list

I'm trying to write a trigger on a table and I can't make this work from these errors below about match count list. I count many times and can't get the problem!
Create Trigger trg_LowSupplyNotify
On Item
After Insert ,Delete
As
Begin
if exists(select 1 from inserted)
Begin
Insert Into LowSupplyNotify
(
[itemNum],
[NumberLeft],
[ManagerMail]
)
Select itemNum ,
NumberLeft,
ManagerMail,
'INSERT' ,SYSTEM_USER
from inserted
END
if exists (select 1 from deleted)
Begin
Insert Into LowSupplyNotify
(
itemNum ,
NumberLeft ,
ManagerMail
)
Select itemNum ,
NumberLeft ,
ManagerMail,
'INSERT' ,SYSTEM_USER
from deleted
End
End
Go
Errors:
Msg 121, Level 15, State 1, Procedure trg_LowSupplyNotify, Line 10 The
select list for the INSERT statement contains more items than the
insert list. The number of SELECT values must match the number of
INSERT columns. Msg 121, Level 15, State 1, Procedure
trg_LowSupplyNotify, Line 25 The select list for the INSERT statement
contains more items than the insert list. The number of SELECT values
must match the number of INSERT columns.
The error tells it all, your select statement has 5 values and the insert has 3 columns defined.
The value 'INSERT' ,SYSTEM_USER have no corresponding column defined in insert statement.
You either add the two columns(if you have defined and exists in your table LowSupplyNotify) else you need to remove the two values('INSERT' ,SYSTEM_USER) from your select statement to get rid of this error.

Extract Row ID from Table - Insert Then Select

Is it Possible to extract the ID of the record being inserted in a table at the time of inserting dat particular record into that table ??? Reference to Sql Server
Read about INSERT with OUTPUT. This is in my experience the easiest way of achieving an atomic INSERT outputting an inserted value.
Example, assuming that Table contains an auto-incremented field named ID:
DECLARE #outputResult TABLE (ID BIGINT)
INSERT INTO Table
(
Field1,
Field2
)
OUPUT INSERTED.ID INTO #outputResult
VALUES
(
....
)
SELECT TOP 1 ID FROM #outputResult
You can select the ID afterwards with
SELECT ##IDENTITY
or
SELECT SCOPE_IDENTITY()

How do I return the column name in table where a null value exists?

I have a table of more than 2 million rows and over 100 columns. I need to run a query that checks if there are any null values in any row or column of the table and return an ID number where there is a null. I've thought about doing the following, but I was wondering if there is a more concise way of checking this?
SELECT [ID]
from [TABLE_NAME]
where
[COLUMN_1] is null
or [COLUMN_2] is null
or [COLUMN_3] is null or etc.
Your method is fine. If your challenge is writing out the where statement, then you can run a query like this:
select column_name+' is null or '
from information_schema.columns c
where c.table_name = 'table_name'
Then copy the results into a query window and use them for building the query.
I used SQL Server syntax for the query, because it looks like you are using SQL Server. Most databases support the INFORMATION_SCHEMA tables, but the syntax for string concatenation varies among databases. Remember to remove the final or at the end of the last comparison.
You can also copy the column list into Excel and use Excel formulas to create the list.
You can use something similar to the following:
declare #T table
(
ID int,
Name varchar(10),
Age int,
City varchar(10),
Zip varchar(10)
)
insert into #T values
(1, 'Alex', 32, 'Miami', NULL),
(2, NULL, 24, NULL, NULL)
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select *
from #T as T2
where T1.ID = T2.ID
for xml path('row'), elements xsinil, type
).value('count(/row/*[#ns:nil = "true"])', 'int') as NullCount
from #T as T1

INSERT INTO With a SubQuery and some operations

I'm trying to insert some data to a table contains two things : "a string" and "maximum number in Order column + 1".
This is my query:
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' , (Max([Order]) + 1)
FROM MyTable
What is going wrong with my query?
I'm using Microsoft SQL Server 2005 SP3.
You can test this query like this:
I don't receive error:
create table #MyTable
(
[Text] varchar(40),
[Order] int NOT NULL
)
INSERT INTO #MyTable([Text],[Order])
SELECT 'MyText' [Text], isnull(max([order]) + 1, 0) [Order]
FROM #MyTable
drop table #MyTable
Original:
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' [Text], max([Order]) + 1 [Order]
FROM MyTable
or
INSERT INTO MyTable ([Text],[Order])
SELECT top 1 'MyText' [Text], max([Order]) + 1 [Order]
FROM MyTable
limit is not valid in SQL Server as far as I know.
Cannot insert the value NULL into column 'Order', table 'master.dbo.MyTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
This means that the Order column isn't allowed to be null, and that the Max([Order]) + 1 part of your column returns NULL.
This is because your table is empty, as you already noticed by yourself.
You can work around this by replacing NULL by a real number in the query, using ISNULL():
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' , (isnull(Max([Order]),0) + 1)
FROM MyTable
Unless he has a column named OrderBy
then he would have to add / assign all values within that Insert especially if the column does not allow for nulls
sounds like fully qualifying the Insert with the dbo.MyTable.Field may make more sense.
also why are you naming fields with SQL Key words...???
INSERT INTO MyTable ([Text],[Order] Values('MyTextTest',1)
try a test insert first..

Select records with order of IN clause

I have
SELECT * FROM Table1 WHERE Col1 IN(4,2,6)
I want to select and return the records with the specified order which i indicate in the IN clause
(first display record with Col1=4, Col1=2, ...)
I can use
SELECT * FROM Table1 WHERE Col1 = 4
UNION ALL
SELECT * FROM Table1 WHERE Col1 = 6 , .....
but I don't want to use that, cause I want to use it as a stored procedure and not auto generated.
I know it's a bit late but the best way would be
SELECT *
FROM Table1
WHERE Col1 IN( 4, 2, 6 )
ORDER BY CHARINDEX(CAST(Col1 AS VARCHAR), '4,2,67')
Or
SELECT CHARINDEX(CAST(Col1 AS VARCHAR), '4,2,67')s_order,
*
FROM Table1
WHERE Col1 IN( 4, 2, 6 )
ORDER BY s_order
You have a couple of options. Simplest may be to put the IN parameters (they are parameters, right) in a separate table in the order you receive them, and ORDER BY that table.
The solution is along this line:
SELECT * FROM Table1
WHERE Col1 IN(4,2,6)
ORDER BY
CASE Col1
WHEN 4 THEN 1
WHEN 2 THEN 2
WHEN 6 THEN 3
END
select top 0 0 'in', 0 'order' into #i
insert into #i values(4,1)
insert into #i values(2,2)
insert into #i values(6,3)
select t.* from Table1 t inner join #i i on t.[in]=t.[col1] order by i.[order]
Replace the IN values with a table, including a column for sort order to used in the query (and be sure to expose the sort order to the calling application):
WITH OtherTable (Col1, sort_seq)
AS
(
SELECT Col1, sort_seq
FROM (
VALUES (4, 1),
(2, 2),
(6, 3)
) AS OtherTable (Col1, sort_seq)
)
SELECT T1.Col1, O1.sort_seq
FROM Table1 AS T1
INNER JOIN OtherTable AS O1
ON T1.Col1 = O1.Col1
ORDER
BY sort_seq;
In your stored proc, rather than a CTE, split the values into table (a scratch base table, temp table, function that returns a table, etc) with the sort column populated as appropriate.
I have found another solution. It's similar to the answer from onedaywhen, but it's a little shorter.
SELECT sort.n, Table1.Col1
FROM (VALUES (4), (2), (6)) AS sort(n)
JOIN Table1
ON Table1.Col1 = sort.n
I am thinking about this problem two different ways because I can't decide if this is a programming problem or a data architecture problem. Check out the code below incorporating "famous" TV animals. Let's say that we are tracking dolphins, horses, bears, dogs and orangutans. We want to return only the horses, bears, and dogs in our query and we want bears to sort ahead of horses to sort ahead of dogs. I have a personal preference to look at this as an architecture problem, but can wrap my head around looking at it as a programming problem. Let me know if you have questions.
CREATE TABLE #AnimalType (
AnimalTypeId INT NOT NULL PRIMARY KEY
, AnimalType VARCHAR(50) NOT NULL
, SortOrder INT NOT NULL)
INSERT INTO #AnimalType VALUES (1,'Dolphin',5)
INSERT INTO #AnimalType VALUES (2,'Horse',2)
INSERT INTO #AnimalType VALUES (3,'Bear',1)
INSERT INTO #AnimalType VALUES (4,'Dog',4)
INSERT INTO #AnimalType VALUES (5,'Orangutan',3)
CREATE TABLE #Actor (
ActorId INT NOT NULL PRIMARY KEY
, ActorName VARCHAR(50) NOT NULL
, AnimalTypeId INT NOT NULL)
INSERT INTO #Actor VALUES (1,'Benji',4)
INSERT INTO #Actor VALUES (2,'Lassie',4)
INSERT INTO #Actor VALUES (3,'Rin Tin Tin',4)
INSERT INTO #Actor VALUES (4,'Gentle Ben',3)
INSERT INTO #Actor VALUES (5,'Trigger',2)
INSERT INTO #Actor VALUES (6,'Flipper',1)
INSERT INTO #Actor VALUES (7,'CJ',5)
INSERT INTO #Actor VALUES (8,'Mr. Ed',2)
INSERT INTO #Actor VALUES (9,'Tiger',4)
/* If you believe this is a programming problem then this code works */
SELECT *
FROM #Actor a
WHERE a.AnimalTypeId IN (2,3,4)
ORDER BY case when a.AnimalTypeId = 3 then 1
when a.AnimalTypeId = 2 then 2
when a.AnimalTypeId = 4 then 3 end
/* If you believe that this is a data architecture problem then this code works */
SELECT *
FROM #Actor a
JOIN #AnimalType at ON a.AnimalTypeId = at.AnimalTypeId
WHERE a.AnimalTypeId IN (2,3,4)
ORDER BY at.SortOrder
DROP TABLE #Actor
DROP TABLE #AnimalType
ORDER BY CHARINDEX(','+convert(varchar,status)+',' ,
',rejected,active,submitted,approved,')
Just put a comma before and after a string in which you are finding the substring index or you can say that second parameter.
And first parameter of CHARINDEX is also surrounded by , (comma).