Reduce values duplication in Insert in T-SQL - sql

I am trying to improve a T-SQL procedure that has been written by a former developer, as you can see it contains quite a big amount of Null:
INSERT INTO #titles
VALUES (
NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,'ABDABCABSBD'
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
,NULL
I don't want to change data that are inserted in the table #title (it is necessary).
What I need to do is storing a certain amount of data (for example here, a multiple number of Null in #storing15Null), in order to use directly this variable instead of copying 15 times Null each time the table #title is defined.
IF #Group = 11
BEGIN
INSERT INTO #titles
VALUES (
#storing15Null
,'ZZZZZZ'
,'PPPPP'
#storing10Null)
END
ELSE IF #Group = 17
BEGIN
INSERT INTO #titles
VALUES (
#storing15Null
,'ABCABCABC'
#storing15Null)
END
For example using a variable or whatever thing that allows me to store a specific amount of items that will go to VALUES.

Any column which has a default does not need to be specified at all. Since nullable columns have a default of NULL, you can simply leave them off the INSERT statement.
For this you need to specify the column names explicitly, you should always do this as columns can be reordered:
INSERT INTO #titles
(col16, col17)
VALUES
('ZZZZZZ', 'PPPPP');

Related

SQL insert statement - FILL null values for all columns except some

I have an insert statement where I only need to fill 15 columns out of 70 - and all the other columns can remain NULL. I would like to find a way to write this statement in a shorter matter without having to write all the null as etc etc
INSERT INTO my_table
SELECT
division_id
,sub_division_id AS sub_division_id
,store
,store_id AS store_id
,store_address
,zip_code
,'202306' AS week
,'2023-02-02' AS date
,'Type' AS type
,'other_string' AS blah
,'Name' AS Name
,NULL AS unimportant_column
,NULL AS unimportant_column_2
,NULL AS unimportant_column_3
,NULL AS unimportant_column_4
,NULL AS unimportant_column_5
,NULL AS unimportant_column_6
,NULL AS unimportant_column_7
,NULL AS unimportant_column_8
,household_id
,NULL AS unimportant_column_9
,NULL
,NULL
,id
,email AS emailaddress
,token
,NULL AS reg
,NULL AS blah
,NULL AS type
,NULL AS del
,NULL AS las
,NULL AS las
,NULL AS fir
,NULL AS las
,NULL AS pro
,NULL AS pro_2
,NULL AS pro_3
,NULL AS prm
,NULL AS pro_5
,NULL AS pro_6
,NULL AS pro_7
,NULL AS pro_8
,NULL AS j4
,NULL AS j4_2
,NULL AS off_1
,NULL AS off02
,NULL AS off03
,NULL AS off04
,NULL AS off05
,NULL AS off_06
,NULL AS off07
,NULL AS of08
,NULL AS off09
,NULL AS off10
,NULL AS off11
,NULL AS off12
,NULL AS off13
,NULL AS of14
,NULL AS off15
,NULL AS off16
,NULL AS off17
,NULL AS off18
,NULL AS off19
,NULL AS off20
,NULL AS off21
,NULL AS off22
,NULL AS off23
,NULL AS off24
,NULL AS dade
,NULL as edyd
FROM some_table x
where flag1 = 1
and flag2 = 7
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42
,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69 ;
I want it to be something like this
INSERT INTO my_table
SELECT
division_id
,sub_division_id AS sub_division_id
,store AS Store
,store_id AS store_id
,store_address as store_nm_addr
,zip_code as zip_code
,'202306' AS week
,'2023-02-02' AS date
,'TYPE' AS TYPE
,'other_string' AS blah
,'Name' AS name
,household_id as household_id
,id as ID
,email AS emailaddress
,token_txt as token
FROM some_table x
where flag1 = 1
and flag2 = 7
;
Ofcourse this does not work as you get this error:
SQL compilation error: Insert value list does not match column list expecting 70 but got 15
But what would be a way to insert just the values you need and default the rest to null values? The "my_table" table must have 70 columns - even though the values in the other columns are null
The problem with your current insert is that if you do not specify any column names then it defaults to expecting all columns. If you explicitly list out the target columns you want, then the omitted names will default to receiving a null value.
INSERT INTO my_table (division_id, sub_division_id,
Store, store_id, store_nm_addr, zip_code, week, date, TYPE, blah, name,
household_id, ID, emailaddress, token)
SELECT
division_id,
sub_division_id,
store,
store_id,
store_address,
zip_code,
'202306',
'2023-02-02',
'TYPE',
'other_string',
'Name',
household_id,
id,
email,
token_txt
FROM some_table x
WHERE flag1 = 1 AND flag2 = 7;

"ORA-00928: missing SELECT keyword”

I am getting "ORA-00928: missing SELECT keyword” error for following query:
insert into candidate_address_t ('ADDRESS_LINE1','ADDRESS_LINE2','CITY','ADDRESS_ID','ZIP','CREATED_BY','MODIFIED_BY','CREATED_DATE','MODIFIED_DATE','ACTIVE_INACTIVE_FLG','ADDRESS_TYPE_ID','CANDIDATE_ID','STATE_ID','GOOGLE_MAP_LINK','SOURCE_TYPE_ID','COUNTRY_TYPE_ID')
values ('test',null,'test','0000','H3X 2P3','9304','9304', sysdate,sysdate,1,'0000','0000','000',null,1,1);
insert into candidate_address_t (ADDRESS_LINE1
,ADDRESS_LINE2
,CITY
,ADDRESS_ID
,ZIP
,CREATED_BY
,MODIFIED_BY
,CREATED_DATE
,MODIFIED_DATE
,ACTIVE_INACTIVE_FLG
,ADDRESS_TYPE_ID
,CANDIDATE_ID
,STATE_ID
,GOOGLE_MAP_LINK
,SOURCE_TYPE_ID
,COUNTRY_TYPE_ID)
values ('test'
,null
,'test'
,'0000'
,'H3X 2P3'
,'9304'
,'9304'
,sysdate
,sysdate
,1
,'0000'
,'0000'
,'000'
,null
,1
,1);
Also, instead of explicitly inserting null into a column, simply omit the column from the list.
Also, you don't need the columns list if you supply a value for every column in the values list.

IF EXISTS SQL Statement won't work

I'm getting this error from the below T-SQL query.
Error message:
Msg 102, Level 15, State 1, Line 13
Incorrect syntax near '101'
Can anyone spot where the error here is? Using Management Studio / SQLServerExpress The desired result is a new record inserted or an existing one update.
Below is my query:
IF EXISTS (SELECT * FROM Product WHERE ProductID = 101)
UPDATE Product SET
ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord',
[description] ='Allianz Landlord', label = 'NULL', AssumptionRef ='NULL',
QuoteProviderKey ='A75',AccidentalDamageCover =0, ProductBenefitGroupID = 11,
IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL',
ProductPolicyView ='NULL', ProductFee =NULL
WHERE ProductID = 101
ELSE
INSERT INTO Product
VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL
WHERE ProductID = 101
Your INSERT statement has a WHERE clause with VALUES set, which isn't valid:
INSERT INTO Product
VALUES 101
,1
,1
,'Landlord'
,'Allianz Landlord'
,'NULL'
,'NULL'
,'A75'
,0
,11
,1
,0
,'NULL'
,'NULL'
,NULL
WHERE ProductID = 101
You are also missing () around the VALUES section, as well as the columns listed out (though, that won't give an error, but you should get in the habit of explicitly listing the columns)
Your statement should look like this:
INSERT INTO Product
(
ProductID
,InsurerID
,CategoryID
,NAME
,[description]
,label
,AssumptionRef
,QuoteProviderKey
,AccidentalDamageCover
,ProductBenefitGroupID
,IsAvailableToBuy
,IsAvalableToDisplay
,PercentageContentsCover
,ProductPolicyView
,ProductFee
)
VALUES
(
101
,1
,1
,'Landlord'
,'Allianz Landlord'
,'NULL'
,'NULL'
,'A75'
,0
,11
,1
,0
,'NULL'
,'NULL'
,NULL
)
Another thing to question is why you're using string 'NULL' values. If you're intending these fields to be NULL, they should be NULL and not 'NULL'
Replace the last where clause because according to your scenario you dont need where in INSERT statement
try running this one
IF EXISTS (SELECT * FROM Product WHERE ProductID = 101) UPDATE Product SET ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord', [description] ='Allianz Landlord', label = 'NULL', AssumptionRef ='NULL', QuoteProviderKey ='A75',AccidentalDamageCover
=0, ProductBenefitGroupID = 11, IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL', ProductPolicyView ='NULL', ProductFee =NULL WHERE ProductID = 101 ELSE INSERT INTO Product VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL
You forgot the begin end
IF (.....)
BEGIN
END
ELSE
BEGIN
END

How to get all id's from inserted table

I am insert bulk of records how to get all those Id's from inserted tables.
I want to use all those ids as forgein keys and insert into another table
INSERT INTO [dbo].[BudCustomers]
([LegalName]
,[EffectiveDate]
,[LawsonCustomerNumber]
,[ChangeReason]
,[ImportedRecord]
,[VersionID]
,[StatusID]
,[CreatedDate]
,[CreatedUserID]
,[LastModifiedDate]
,[LastModifiedUserID]
,[CustomerGroupID])
SELECT CustomerName
,'1900-01-01 00:00:00.000'
, CASE WHEN PATINDEX('%[0-9]%', CustomerName) > 0
THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName),
LEN(CustomerName)), ')', '')
ELSE 0 END
,''
,1
,1
,1
,GETDATE()
,'Import'
,GETDATE()
,'Import'
,NULL
FROM External_Blk_Itm_Contracts
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals)
Use OUTPUT clause:
CREATE TABLE #temp (CustomerId <datatype> );
INSERT INTO [dbo].[BudCustomers]
([LegalName]
,[EffectiveDate]
,[LawsonCustomerNumber]
,[ChangeReason]
,[ImportedRecord]
,[VersionID]
,[StatusID]
,[CreatedDate]
,[CreatedUserID]
,[LastModifiedDate]
,[LastModifiedUserID]
,[CustomerGroupID])
OUTPUT inserted.CustomerId
INTO #temp
SELECT CustomerName
,'1900-01-01 00:00:00.000'
, CASE
WHEN PATINDEX('%[0-9]%', CustomerName) > 0
THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName),
LEN(CustomerName)), ')', '') ELSE 0 END
,''
,1
,1
,1
,GETDATE()
,'Import'
,GETDATE()
,'Import'
,NULL
FROM External_Blk_Itm_Contracts
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals)
SELECT *
FROM #temp;

INSERT INTO Statement only for those who don't have already an entry

I have 2 tables: cSc_UserClassSettings and cSc_User
I want to INSERT all User in cSc_UserClassSettings from cSc_User using this INSERT Statement:
INSERT INTO [cSc_UserClassSettings]
([RSRC]
,[Deleted]
,[DateNew]
,[DateChanged]
,[UserNew]
,[UserChanged]
,[camosGUID]
,[UserGUID]
,[ClassName]
,[WriteByOpen]
,[DefaultReadAccess]
,[DefaultWriteAccess]
,[Summary])
SELECT
0
,0
,getdate()
,NULL
,camosGUID
,NULL
,NEWID()
,camosGUID
,'cQ_RootOffer_C'
,0
,0
,0
,0
FROM [cSc_User]
But some users already have an entry in cSc_UserClassSettings and for those it should not make an entry.
If it is neccessary cSc_UserClassSettings has a Foreign Key on cSc_User with cSC_UserClassSettings.UserGUID = cSC_User.camosGUID
I've tried this:
INSERT INTO [cSc_UserClassSettings]
([RSRC]
,[Deleted]
,[DateNew]
,[DateChanged]
,[UserNew]
,[UserChanged]
,[camosGUID]
,[UserGUID]
,[ClassName]
,[WriteByOpen]
,[DefaultReadAccess]
,[DefaultWriteAccess]
,[Summary])
SELECT
0
,0
,getdate()
,NULL
,camosGUID
,NULL
,NEWID()
,camosGUID
,'cQ_RootOffer_C'
,0
,0
,0
,0
FROM [cSc_User]
WHERE NOT EXISTS(
select *
from cSc_UserClassSettings
where classname = 'cQ_RootOffer_C' and deleted = 0
)
But it returns 0 values.
Any ideas how I could solve that?
Thanks in advance.
If you want to insert record in cSc_UserClassSettings from cSC_User table but those are not in already in cSc_UserClassSettings then you can try this Select Query
SELECT
0
,0
,getdate()
,NULL
,camosGUID
,NULL
,NEWID()
,camosGUID
,'cQ_RootOffer_C'
,0
,0
,0
,0
FROM [cSc_User]
WHERE cSC_User.camosGUID NOT IN (
Select UserGUID
From cSc_UserClassSettings
)