Replace text within a Query - sql

I have a very long list of data that i need to insert into a table. I have a pre-formatted list of queries that does it, in which i go through each query and replace 'X' with part of an item number. Is there any way that i can save myself typing or copying the text dozens of times over by just replacing 'X' with the text I need?
My set of queries is much longer than this but looks like
Insert into Inventory_Ingredients
Values ('X300', 1001, '30label', 1, '0', 0)
Insert into Inventory_Ingredients
Values ('X300', 1001, '30b', 1, '0', 0)
Insert into Inventory_Ingredients
Values ('X300', 1001, 'Shrink30', 1, '0', .50/100)
Insert into Inventory_Ingredients
Values ('X300', 1001, 'recipeX', 1, '0', 1.00/100)
Insert into Inventory_Ingredients
Values ('X300', 1001, 'wiznic100', 0*30/100, '0', 2.00/100)
Insert into Inventory_Ingredients
Values ('X300', 1001, 'vg', 30-(select sum(inventory_ingredients.quantity)
from inventory_ingredients
where itemnum='recipeX'
group by itemnum)-(0*30/100), '0', 2.00/100)

Any reason dynamic SQL wouldn't work for what you're doing? Very useful in situations like this. Or if the X is just for values being inserted rather than for changing the query structure, variables would likely do the trick. Even so, I bet one of the two options will do it for you. Here's a good site for dynamic SQL help... https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

Related

Insert NULL values into INT & STRING columns

I need to insert null values ​​in integer and string columns but in the data set that it obtains before obtaining values ​​"---" for the case of string and "NA" for the case of INT, necessary when you have those values ​​are inserted as void I'm using SQL Sever and my query is like that.
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, MICRO_WEEK, MICRO_DIVISION, MICRO_SUBDIVISION, MICRO_CODE_COUNTRY, MICRO_COUNTRY, MICRO_CODE_CENTER, MICRO_CENTER, MICRO_FREQ, MICRO_TOTAL_M, MICRO_TOTAL_Y, MICRO_TOTAL_Z, MICRO_ID_PROCESS, MICRO_DESC_PROCESS, MICRO_TOTAL_A, MICRO_TOTAL_B, MICRO_TOTAL_C, MICRO_ID_POINT, MICRO_DESC_POINT, MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F) VALUES
(
'2019-01-15',
'2019',
'1',
'3',
'X',
'Y',
'P001',
'USA',
'USA1',
'USA2',
'Daily',
'2',
'2',
'0',
'158',
'Enva',
'2',
'2',
'0',
'344',
'2',
'---', --NULL
'---', --NULL
'NA', --NULL
'NA', --NULL
'NA' --NULL
)
To insert NULL values use the NULL keyword. As in:
insert into t (col)
values (null);
To insert the default value, which is usually null, just leave the column out of the column list entirely:
insert into t (col1)
values ('happy value');
col2 will be set to its default value -- which is NULL if no other default is defined.
If you are inserting values from another source, then use try_convert() or nullif() For example:
insert into t (col_str, col_int)
values (nullif(#col_str, '---'), try_convert(int, #col_int));
Also, as a matter of standard practice, you should always use query parameters to supply any literal values to your queries, to avoid "SQL injection" issues. For instance, your query would now read:
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, [...])
VALUES(?, ?, ? [...])
Notice the ? symbols and notice also that they are not in quotes.
Then, when you execute the query, you supply both the SQL string and, separately, an array of values that are to be substituted for each ? in order of occurrence. Now, SQL cannot misinterpret any value as "part of the SQL," because it isn't. Different sets of parameter values can be supplied to the same SQL string each time.
You can use functions such as NULLIF() as mentioned in BJones' comment: NULLIF('---', ?) ... the parameter's value will be passed to the NULLIF function as its second argument. I think that's a fine way to handle your requirement (and it should have been offered as "an answer").
It really depends where the values are coming from, but if for example this insert is inside a Stored Procedure and the values are coming in via parameters then the following shows how to ensure null values for the cases specified. (Irrelevant columns left out for brevity):
INSERT INTO BOEMIC01 (... MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F)
select ...
, case when #MICRO_CODE_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, case when #MICRO_DESC_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, try_convert(int, #MICRO_TOTAL_D)
, try_convert(int, #MICRO_TOTAL_E)
, try_convert(int, #MICRO_TOTAL_F)
However if you are passing this data from a client application then convert it client side.

Tsql Inserting Unordered Sequence

I'm trying to insert an unordered sequence (list) into 2 kind of table explained here:
Table has one INT column
Table has several columns, one of them is an INT column (which I will use to insert the data)
So, here is the example;
List; (1, 3, 55, 3, 56456, 45)
Table; (Value INT)
I'm not looking for any solution, but a solution which is not including 'parse, split etc.' operations.
Expected solution:
INSERT INTO Table(Value)
VALUES(anyList)
Expected solution 2:
INSERT INTO Table(Value)
VALUELIST(anyList)
OR
INSERT INTO Table(Value)
VALUETABLE(anyList)
You can't directly insert like following.
INSERT INTO Table(Value)
VALUES (1, 3, 55, 3, 56456, 45)
You will get following error.
Msg 110, Level 15, State 1, Line 1 There are fewer columns in the
INSERT statement than values specified in the VALUES clause. The
number of values in the VALUES clause must match the number of columns
specified in the INSERT statement.
SQL Server will only accept your Insert if you give like following.
INSERT INTO Table(Value)
VALUES (1),(3),(55), (3), (56456), (45)
If you are getting the list as a string, in that case you need to convert it into appropriate format before inserting, like following.
DECLARE #xml as xml
DECLARE #list as varchar(max)
SET #list='(1, 3, 55, 3, 56456, 45)'
set #list = REPLACE(REPLACE(#list,'(',''),')','')
SET #xml = cast(('<X>'+replace(#list,',' ,'</X><X>')+'</X>') as xml)
INSERT INTO [Table](Value)
SELECT N.value('.', 'int') as value FROM #xml.nodes('X') as T(N)

What's wrong with this SQL INSERT statement?

I want to insert a certain value into a certain field of five different rows altogether. But whenever I run this query it doesn't get executed. What's wrong with it, and how can I fix it?
INSERT INTO `employee`(`password`) VALUES ('abc') WHERE `id` IN (1,2,3,4,5);
An INSERT can't have a WHERE clause. It looks like you meant to do an update:
UPDATE `employee`
SET `password` = 'abc'
WHERE `id` IN (1,2,3,4,5);
Or perhaps a multi-row insert:
INSERT INTO `employee` (`id`, `password`)
VALUES (1, 'abc'), (2, 'abc'), (3, 'abc'), (4, 'abc'), (5, 'abc');
Also, FYI, you really shouldn't be storing passwords as plain text, which it looks like you may be doing.

Why this insert query go into error?

I am very new to Microsoft SQL Server and I have a problem with this INSERT query that inserts a new record in a very very big table (it has many columns).
I have this query:
INSERT INTO VulnerabilityAlertDocument ([Id],
[VulnerabilityAlertId],
[SourceId],
[BugTraqID],
[Title],
[StatusID],
[CVE],
[Published],
[LastUpdated],
[Remote],
[Local],
[Credibility],
[Classification],
[Availability],
[Ease],
[Authentication],
[CVSS2_BaseScore],
[CVSS2_TemporalScore],
[CVSS2_BaseVector],
[CVSS2_TemporalVector],
[CVSS1_BaseScore],
[CVSS1_TemporalScore],
[NVD_CVSS2_BaseScore],
[NVD_CVSS2_ComponentString],
[ImpactRating],
[Severity],
[EaseofExploit],
[UrgencyRating],
[LastChange],
[ShortSummary],
[Impact],
[TechnicalDescription],
[AttackScenario],
[Exploit],
[Credit],
[URL],
[AlertStatusId],
[Type],
[DetailLevel],
[Language],
[dd])
VALUES('10000',
'10000',
'TEST',
'5',
'TEST TITLE',
'1',
'TEST CVE',
'1998-04-30 00:00:00.000',
'2007-11-05 16:32:34.000',
'TEST REMOTE',
'TEST LOCAL',
'TEST CREDIBILITY',
'TEST CLASSIFICATION',
'TEST Availability',
'TEST EASE',
'TEST Authentication',
'TEST CVSS2_BaseScore',
'TEST VSS2_TemporalScore',
'TEST CVSS2_BaseVector',
'TEST VSS2_TemporalVector',
'TEST CVSS1_BaseScore',
'TEST CVSS1_TemporalScore',
'TEST NVD_CVSS2_BaseScore',
'TEST NVD_CVSS2_ComponentString',
'2',
'3',
'10',
'7',
'TEST LastChange',
'TEST ShortSummary',
'TEST IMPACT',
'TEST TechnicalDescription',
'TEST AttackScenario',
'TEST Exploit',
'TEST Credit',
'TEST URL',
'5',
'3',
'1',
'TEST Language',
'NULL');
In which I insert a specific value into a specified column (I specify columns by the first query section, and I specify the related values by the second section of the query)
The problem is that when I try to execute the previous query I obtain the following error
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'VulnerabilityAlertDocument' when
IDENTITY_INSERT is set to OFF.
Why? What does this mean? How can I change my query to solve this problem and so insert the record in my table?
Try SET IDENTITY_INSERT VulnerabilityAlertDocument ON before INSERT
After INSERT, add SET IDENTITY_INSERT VulnerabilityAlertDocument OFF
you have an identity column then you don't have to insert the Id, you have to delete Id from your query and the value of the Id
Remove the [Id] column from the list of columns and its corresponding value '10000'. The error is due you are trying to populate a column with a value and SQL is complaining that a automated handled value just he can provide.
BTW, you don't need to quote your numeric values if that columns are of numeric type.
Use SET IDENTITY_INSERT ON before your query.
Identity columns are auto-increasing and so do not allow insertion.
You need to explicitly state that you want to insert data into the column so that SQL server allows it.
Make sure you do not insert duplicate values for this column.
The best practice is to avoid inserting values into IDENTITY column.
Remove "[ID]"
write it like that:
INSERT INTO your table name
For example:
If you have Instructor table with attributes ID, name and dept_name
Use: Insert Command like bellow
Insert Into Instructor (ID, name, dept_name) Values (11111, 'Andrea', 'Biology');
Try this and let me show you result !!

SQL Oracle error

insert into tour_concerts values
('1', to_date('02/08/1974', 'DD/MM/YYYY'), 'Misc Concerts', 'UK'),
insert into tour_concerts values
('2', to_date('01/01/1977', 'DD/MM/YYYY'), 'The Hoople North America Your', 'USA'),
insert into tour_concerts values
('3', to_date('05/09/1971', 'DD/MM/YYYY'), 'Sheer Heart Attack UK tour', 'UK'),
insert into tour_concerts values
('4', to_date('09/02/1972', 'DD/MM/YYYY'), 'Works Japan tour', 'Japan'),
insert into tour_concerts values
('5', to_date('03/10/1975', 'DD/MM/YYYY'), 'Magic Tour', 'UK'),
insert into tour_concerts values
('6', to_date('02/01/1974', 'DD/MM/YYYY'), 'Freddie Mercury Tribute Concert for AIDS Awareness', 'UK');
SQL> #tour_concerts1;
('6', to_date('02/01/1974', 'DD/MM/YYYY'), 'Freddie Mercury Tribu
te Concert for AIDS Awareness', 'UK')
*
ERROR at line 2:
ORA-12899: value too large for column "S3327043"."TOUR_CONCERTS".
"TYPE" (actual: 50, maximum: 30)
Can someone help me fix this error?
OKAY I'VE FIXED IT
This error is clearly stating that you're trying to insert a too long varchar value in the 3rd column of the tour_concerts table.
You can fix this by:
Altering the table's structure to make the column accept more than 30 characters. For instance, 50 is the number of characters of the statement that is failing.
alter table tour_concerts modify column_name varchar2(50)
Use the Oracle substr function:
`insert into tour_concerts values ('6', to_date('02/01/1974', 'DD/MM/YYYY'), substr('Freddie Mercury Tribute Concert for AIDS Awareness', 0, 30), 'UK');
If these records are inserted thorugh an application via jdbc for instance, trim user input to not exceed your table's maximum sizes.
Error is clear: TOUR_CONCERTS.TYPE field allows 30 chars, no more, and you're trying to insert a longer string.
You have two ways to solve this:
Shorten string you're inserting (Freddie Mercury Tribute Concert for AIDS Awareness is longer than 30 chars)
Change your table definition and set TOUR_CONCERTS.TYPE field length to an higher value (say 200?)
Huh.I think you should alter your table.30 is too short.
If your DB is oracle:
alter table YOURTABLE alter column 'S3327043' varchar(100)
Check this article it seems your trying to insert longer value than the field, make the fields bigger than the maximal value you could need.