Insert Clause and receiving error for NULL value into column - sql-server-2012

Trying to create a lookup to run an import for a file into the database, and within the query I created that would insert an address from the import file if it was not found, I am getting the Error Code 515 stating that it "cannot insert the value NULL into column 'R_Identity'; column does not allow nulls; INSERT fails."
This is the query I created:
Declare #CONSIGNEEROWID UniqueIdentifier
Declare #STREET Varchar(40)
Declare #CITY VarChar(30)
Declare #STATE Char(5)
Declare #ZIP VarChar(20)
Declare #COMPANYID Char(2)
begin
if not exists (Select * from idaddress where idaddress.address_1 = #street and idaddress.city = #city and idaddress.state = #state and idaddress.zip = #zip)
begin
insert into idaddress (idaddress.address_1, idaddress.city, idaddress.state, idaddress.zip)
values (#street, #city, #state, #zip)
end
end
Select #CONSIGNEEROWID AS CONSIGNEEROWID
I tried seemingly everything to fix the error code, but to no avail. The query is ideally for when a txt file is imported, this specific lookup in the mapping would create the address found in the file, if the lookup can not locate the address, i.e. address_1, city, state, zip, country.

Related

String that contains a SELECT with several pairs of variables and values. Using EXEC gives me an undeclared variable error

The process is more complex than the previous one.
I have a stored procedure that retrieves the variable #parameters_list NVARCHAR(2000).
This #parameters_list variable contains a series of parameters that I retrieve from a transactional website. Usually, it contains a series of parameters with their respective values. The parameters vary depending on the type of transaction being executed.
Here is a more complete description of the process:
Suppose, that #parameters_list comes with the following data from the website
#parameters_list = 'id_client=1;id_dealer=1;id_country=1;id_region=5;id_city=2;sede=2;id_tower=8;main_code=CHI-01-01;id_location=2;city=Main City;data_name=Box 01;title=Major KPI;tittle2=Detecting relevant Data;detail=none'
Inside the stored procedure, I have in part the following declarations and creation of a temporary table:
DECLARE #id_client INT,
#id_dealer INT,
#id_country INT,
#id_region INT,
#id_city INT,
#id_tower INT,
#main_code VARCHAR(120),
#id_location INT,
#city VARCHAR(50),
#data_name VARCHAR(100),
#detail VARCHAR(100),
#title VARCHAR(200),
#title2 VARCHAR(300)
DECLARE #stringData NVARCHAR(2000),
#data_key VARCHAR(30)
DECLARE #ident INT
CREATE TABLE [dbo].[#TEMP_DATA](
[ident] [int] IDENTITY(1,1) NOT NULL,
[data_key] [varchar](100) NULL,
[data_value] [varchar](100) NULL
) ON [PRIMARY]
Later, I execute another stored procedure (PANKI_UTILS..SP_KEY_VALUE_PARAMETER) whose main task is to separate the variables with their respective values. Then, the result is stored in the temporary table #TEMP_DATA.
EXEC PANKI_UTILS..SP_KEY_VALUE_PARAMETER
#parameters_list,
';',
'=',
#ident output
INSERT INTO
#TEMP_DATA
SELECT
[key],
value
FROM PANKI_UTILS..KEY_VALUE
WHERE ind = #ident
ORDER BY [key]
The content of the #TEMP_DATA table is as follows:
What the image shows is a table where the column data_key is the name of the variable and "data value" the value of that variable.
Finally, I store all the content of the table in a #stringData variable
SET #stringData = (SELECT string_agg('#'+CAST(data_key AS VARCHAR(30)) +'='+ CAST(data_value AS VARCHAR(500)), ',') FROM #TEMP_DATA)
SELECT #stringData
#city=Main City,#data_name=Box 01,#detail=none,#id_city=2,#id_client=1,#id_country=1,#id_dealer=1,#id_location=2,#id_region=5,#id_sede=2,#id_tower=8,#main_code=CHI-01-01,#title=Major KPI,#tittle2=Detecting relevant Data
That's why I'm looking for a way to retrieve the variables in the form of; #city, #data_name and etc.
An alternative was to use the sp_executesql command, but I don't really know how to use it to retrieve those variables.
If you can help me, I would appreciate it. Thanks.
The TSQL you provide as a parameter to execute is run in a different scope than your parent script. It doesn't have access to local variables declared outside of it.
If you need to use execute, try something like this:
declare #string_data varchar(max);
SET #string_data = '
declare #City varchar(255), #Product varchar(255) , #Zip varchar(255);
SELECT #city=''Baltimore'', #product= ''car'', #zip=''630930'';
SELECT #city AS city, #product AS product, #zip AS zip;
';
EXEC(#string_data);
But you might be able to get away without using it:
declare #City varchar(255), #Product varchar(255) , #Zip varchar(255);
SELECT #city='Baltimore', #product= 'car', #zip='630930';
SELECT #city AS city, #product AS product, #zip AS zip;
When you use EXEC(#String), you're opening a new session and starting a new transaction. That new session that is opened is not aware of any variable from the calling session that executed the EXEC command.
Further, it doesn't really look like you need to use dynamic SQL and execute right here.
Without know what the rest of your query looks like, try this.
SELECT #city=Baltimore, #product= car, #zip=630930
SELECT #city AS city, #product AS product, #zip AS zip

Hash saved in Chinese instead of standard

I created a procedure in SQL Server to enter a new user.
When I'm going to create the hash password that appears in the Chinese language, I couldn't understand why.
Can someone help me with the solution and also explain to me why this happened?
Script:
ALTER PROCEDURE [Administrative].[spInsertUser]
(#Name Nvarchar(50),
#Surname Nvarchar(Max),
#Email Nvarchar(1000),
#PasswordHash Nvarchar(Max),
#EmailConfirmed Bit,
#Lockout Bit,
#TimeZone Nvarchar(6))
AS
BEGIN
DECLARE #Id Bigint;
DECLARE #NewPasswordHash Varbinary(Max);
SET #NewPasswordHash = HASHBYTES('SHA2_512', #PasswordHash);
INSERT INTO Administrative.Users ([Name], Surname, Email, PasswordHash,
EmailConfirmed, Lockout, TimeZone, Active)
VALUES (#Name, #Surname, #Email, #NewPasswordHash,
1, 0, #TimeZone, 1)
SET #Id = ##Identity
SELECT #Id AS Id
END
Result:
Created with varbinary:
Error
Msg 257, Level 16, State 3, Administrative.spInsertUser Procedure, Line 0 [Batch 8 Start Line]
Implicit cast from varchar data type to varbinary is not allowed. Use the CONVERT function to run this query.

How to pass value to stored procedure with spatial/geography data type using SQL query

I'm a student and after 2H searching answer I'm hopping that someone can help me here.
I created a stored procedure that expects a name, address and geography location then adds a new branch to the Branches table. I'm trying to pass a geography value using a new query, but I keep getting a syntax error.
Stored procedure :
create procedure AddBranch
#Name nvarchar(50),
#Address nvarchar(100),
#GeographicLocation geography
as
begin
SET NOCOUNT ON
insert into Branches (Name, Address, GeographicLocation)
values (#Name, #Address, #GeographicLocation)
select BranchID
from Branches
where BranchID = SCOPE_IDENTITY()
end
Query:
exec AddBranch
#Name = 'Some Name',
#Address = 'Some Address',
#GeographicLocation = geography::Point(47.65100, -122.34900, 4326)
Error:
Incorrect syntax near'::'
Is there a way to pass geography data to a stored procedure?
In addition to enclosing the arguments in quotes, you need to assign the method result to a local variable in order to pass the value as a parameter in T-SQL:
DECLARE #geographyPoint geography = geography::Point('47.65100', '-122.34900', '4326');
exec AddBranch
#Name = 'Some Name',
#Address = 'Some Address',
#GeographicLocation = #geographyPoint;
as a sidenote:
create procedure dbo.AddBranch --always specify schema
#Name nvarchar(50),
#Address nvarchar(100),
#GeographicLocation geography
as
begin
SET NOCOUNT ON
SET XACT_ABORT ON --should be in every data modification SP
insert into dbo.Branches (Name, Address, GeographicLocation) --schema!
output inserted.BranchID --this
values (#Name, #Address, #GeographicLocation)
select SCOPE_IDENTITY() BranchID --or this
--absolutely no need in another read operation from persistent table
end
Put the values into quotes like this
exec AddBranch
#Name = 'Some Name',#Address = 'Some Address',
#GeographicLocation = geography::Point('47.65100', '-122.34900', '4326')
go
Although this might not work depending on how this custom Geography type expects its values, it will solve the syntax error.

Stored Procedure Cross Table ID Input

I'm trying to insert other table's IDs (Company and Bank) into the uBankID and uCompanyID of the EndUser table and the BankID of the Company table on INSERT.
Whatever way I do this, the required fields aren't being populated, what am I doing wrong? I had a look at an inline select statement at the ID to try and grab it but couldn't fathom it and it wouldn't compile.
The variables are all present and correct in the backend and are being parsed through, all but these IDs, as nothing is going wrong with the C# I'm thinking there's something amiss with my SQL, especially as I'm fairly new to stored procedures.
Any help would be greatly appreciated.
Code (slimmed down):
CREATE PROCEDURE [ProcedureInsert]
#Title nvarchar(10),
#FirstName nvarchar(50),
#LastName nvarchar(50),
#Organisation nvarchar(50),
#Address nvarchar(50),
#uBankID int,
#uCompanyID int,
#BankID int,
#SortCode int,
#AccountNumber nvarchar(50),
#AccNameHolder nvarchar(50),
#cId int output,
#bId int output,
#euId int output
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [Bank](SortCode, AccountNumber, AccNameHolder)
VALUES(#SortCode, #AccountNumber, #AccNameHolder)
SET #bId = SCOPE_IDENTITY();
INSERT INTO [Company](Organisation, Address, BankID)
VALUES(#Organisation, #Address, #bId)
SET #cId = SCOPE_IDENTITY();
INSERT INTO [EndUser](Title, FirstName, LastName, uBankID, uCompanyID)
VALUES(#Title, #FirstName, #LastName, #uBankID, #cId)
SET #euId = SCOPE_IDENTITY();
END
You need to declare the variables. And Tab Alleman is right, get rid of the unused parameters.
DECLARE #cId int;
DECLARE #bId int;
DECLARE #euId int;
INSERT INTO [BAD](SortCode,AccountNumber,AccNameHolder)
VALUES('1234','a234','Test Name')
SET #bId=SCOPE_IDENTITY();
INSERT INTO [Company](Organisation,Address1, Address2,City,County,PostCode,Telephone,BankID)
VALUES('AnOrganisation','addressesss','Address2','City','County','PostCode','0123one', #bId)
SET #cId=SCOPE_IDENTITY();
INSERT INTO [EndUser](Title,FirstName,LastName,Email,uBankID,uCompanyID)
VALUES('Sitle','Fiame','astName','vv#Email',#bId,#cId)
SET #euId=SCOPE_IDENTITY();
EDIT
Remove those parameters if they're not being used, but they weren't in the sample code, else leave them, obviously.
Also, I used single quotes to dump in the data into the table rather than variables, if it's not working then there's something wrong with the bank end code.

Stored Procedure for Multi-Table Insert Error: Cannot Insert the Value Null into Column

Good Evening All,
I've created the following stored procedure:
CREATE PROCEDURE AddQuote
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare #CompanyName nvarchar(50),
#Addr nvarchar(50),
#City nvarchar(50),
#State nvarchar(2),
#Zip nvarchar(5),
#NeedDate datetime,
#PartNumber float,
#Qty int
-- Insert statements for procedure here
Insert into dbo.Customers
(CompanyName, Address, City, State, ZipCode)
Values (#CompanyName, #Addr, #City, #State, #Zip)
Insert into dbo.Orders
(NeedbyDate)
Values(#NeedDate)
Insert into dbo.OrderDetail
(fkPartNumber,Qty)
Values (#PartNumber,#Qty)
END
GO
When I execute AddQuote, I receive an error stating:
Msg 515, Level 16, State 2, Procedure AddQuote, Line 31
Cannot insert the value NULL into column 'ID', table 'Diel_inventory.dbo.OrderDetail'; column does not allow nulls. INSERT fails.
The statement has been terminated.
I understand that I've set Qty field to not allow nulls and want to continue doing so. However, are there other syntax changes I should make to ensure that this sproc works correctly?
Thanks,
Sid
You have an ID column in the OrderDetail table
You are not giving a value for ID in the INSERT
so
change the OrderDetail insert to give a value
or ensure the column has an IDENTITY
or ensure it has a default (not useful if it's the PK but generally it's an option)
Looks to me like you forgot to enable "identity specification" for the ID column of the OrderDetail table. It has nothing to do with your stored procedure per se.
You will need to recreate the table to make the ID column have IDENTITY, but SQL Management Studio will script that for you.