How to check if number exists in SQL - sql

I have a stored procedure and I have to modify it so it does not accept an empty string nor a null.
I currently have this as part of the stored procedure
IF NOT EXISTS (SELECT * FROM dbo.tblUserCode WHERE iUserID = #UserID)
BEGIN
INSERT INTO dbo.tblUserCode (iUserID, sCode)
VALUES (#UserID, #Unlock)
END
However I don't want to enter anything into the table if the value is a null or string. The table only has user ids that have a code. It is currently storing 0s and empty strings when a user gets created and they leave the slot blank. I know it's this line because my access code checks if the code is 4 digits long and if it is only digits but when it returns a string that gets stored into the table.

It looks like you are using MS SQL Server (not clear from your tags) as your DBMS. In that case:
NOT ISNULL(sCode,'')=''
Will check if sCode is not Null or an empty string. Add it to your IF statement.

Related

SQL Server stored procedure: how to return column names/values of type failures in variable?

Ambiguous thread name, I apologize. I am not new to SQL, but I'm new to coding longer stored procedures so I don't deal with variables much outside of passing through maybe a table name or returning row count, etc.
I have a stored procedure that is executing an insert from a staging table to a fact table. There are a couple type casts in the insert.
If the insert fails due to a typecast. Is there any way to return the name of the column that failed, along with what the failed value was? How would I code that? I know that Try_parse would make it so the stored procedure doesn't fail on type cast failure, but I want to be able to pass back exactly what column and value failed.
I show an example here:
Create Procedure dbo.Example_Insert
#updateUser varchar(255)
As
Begin
Insert Into dbo.Energy_Costs (Energy_Cost_Id, Project_Id, Propane_Cost_Dollars,
Electricity_Cost_Dollars, Fuel_Savings_Evaluator)
Select
Next Value For energy_cost_id,
r.project_id,
Cast(r.propane_cost_dollars As Decimal(18,2)),
Cast(r.electricity_cost_dollars As Decimal(18,2)),
#update_user fuel_savings_evaluator
From
staging_table r
return ##ROWCOUNT
end
You can use CURSOR in sql then insert one line at a time. When insert fail return value currently row error.
I hope my idea suitable with you.

SQL syntax error in updating a database value

I'm update the money for one person only in a database. The money is saved as a currency and the email as a string. My SQL is throwing a syntax error
ADOQuery.sql.text:= ' UPDATE TblPlayerdetails SET Money = "' + Inttostr(NewAmount) + '" WHERE Email = "' + Playersemail + '"';
Newamount is an integer and email is a string.
I was hoping you would manage to work out what to do from the documentation I linked in comments, but on reflection I thought I had better provide a correct answer.
Set up the following code
procedure TForm1.Button1Click(Sender: TObject);
begin
AdoQuery2.SQL.Text := 'update moneytable set money = :money where id = :id';
AdoQuery2.Parameters.ParamByName('ID').Value := 1;
AdoQuery2.Parameters.ParamByName('Money').Value := 99;
AdoQuery2.ExecSQL;
end;
The line
AdoQuery2.SQL.Text := 'update moneytable set money = :money where id = :id';
sets up a parameterised UPDATE statement. The :id and :money are placeholders for parameter values which will be provided separately. The parameter names are ID and Money, though they could be given other names. Note that you could set up AdoQuery2's SQL.Text in the IDE at design time if you wanted to.
The next two lines
AdoQuery2.Parameters.ParamByName('ID').Value := 1;
AdoQuery2.Parameters.ParamByName('Money').Value := 99;
specify the values which the parameters are to be set to for when the UPDATE is actually executed. The ID value is the Row iD (aka primary key) of the row in the table which is to be updated. Before the UPDATE staement is actually executed, the AdoQuery parses the SQL and creates the parameters if they don't alteady exist (you can create them at design time in the IDE by editing the Parameters property of the AdoQuery.
Finally
AdoQuery2.ExecSQL;
is what actually executes the UPDATE statement. Note that you can repeat the steps of setting the parameter values and calling ExecSQL as many times as you want.
The main thing which was wrong with your UPDATE statement was that you were using double-quote (") marks, whereas when a SQL statement needs quote marks (and values of numeric columns do NOT) they should be single quotes('). A complication when constructing a SQL statement in Delphi code is that its syntax requires single quotes which are to be embedded in the SQL to be doubled up.
Note also that you should always used parameterised SQL for your SELECT, UPDATE, INSERT and DELETE statements as this helps protect your app against Sql injection. Making, say, an unparameterised statement accessible to the user can allow a malicious user to attempt to execute any SQL they wish.
In your question, you did not indicate what type of column is 'Money'. If it's varchar, char, then I understand why you might convert NewAmount to a string.
However, if the database expects numeric value (because the field is of type int, double, dec, or float), the syntax would be SET Money= '+ NewAmount +'.

sql stored procedure, concat string table name with parameter value

i have created a stored procedure that contains a parameter. I want to use this parameter as part of the table name. there are 2 tables a user can choose
by entering the final 4 values
[Summary_tableStore4302]
[Summary_tableStore4304]
i want the numericalportion as the parameter. This will be executed in Tableau, so user can enter either 4302 or 4304, the select statement will grab data from this table.
the trouble I am having (i think) is trying to concat the string portion of the table name to the parameter value and using it within the select statement
CREATE PROCEDURE testTableau4
#BM1 int = 0
Set #tableName = concat('[Summary_tableStore',#BM1,']' );
select * from #tableName as t1
End
Go
what is the proper way to concat a string value and integer parameter value and use it as a table name within Select statement, specifically within a Stored Procedure. thank you!

SQL Server Stored Procedure INSERT NVARCHAR(MAX) not saving

I have a rather simple SQL Server stored procedure with 2 input parameters, a name which is nvarchar(100) and results which is nvarchar(max).
The stored procedure just does an insert - nothing more.
INSERT INTO TableX (name, results)
VALUES (#Name, #Results)
Results is a | delimited file serialized to a string. Sometimes when this stored procedure is run, the row in the table only has the name and results is blank. No SQL errors. It isn't just because of length of results because some of the calls that work are longer then some of the calls that end up empty. I did catch that some of the entries contain single quotes so I stripped out single quotes and that didn't help.
Any ideas?
Here is the stored procedure:
CREATE PROCEDURE [dbo].[tempdata_SaveMarketStatsToCache]
(#ScreenName NVARCHAR(100),
#Results NVARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO TempData_MarketStatsCache (MarketStatsKey, Results)
VALUES (#ScreenName, #Results)
END
Stored Procedure is called from .NET. SQLDbType.NVarchar with length of -1
UPDATE: I suspect it is the size of the string being passed. The smallest string that is failing is just under 250K characters. This is OK for NVARCHAR(max), but it seems that something happens during the INSERT.
UPDATE 2: Turns out it was an issue with SQL Server Managment Studio. I was right clicking on table and choosing edit 200 rows. That showed the column as empty for the rows with the large results (over 200K characters). If I simply ran a query the column values showed.
Turns out it was a SQL Server Management Studio issue making it seem like data wasnt inserted. See Update 2 in the question.

SQL update if exist and insert else and return the key of the row

I have a table named WORD with the following columns
WORD_INDEX INT NOT NULL AUTO_INCREMENT,
CONTENT VARCHAR(255),
FREQUENCY INT
What I want to do is when I try to add a row to the table if a row with the same CONTENT exits, I want to increment the FREQUENCY by 1. Otherwise I want to add the row to the table. And then the WORD_INDEX in the newly inserted row or updated row must be returned.
I want to do this in H2 database from one query.
I have tried 'on duplicate key update', but this seems to be not working in H2.
PS- I can do this with 1st making a select query with CONTENT and if I get a empty result set, makeing insert query and otherwise making a update query. But as I have a very large number of words, I am trying to optimize the insert operation. So what I am trying to do is reducing the database interactions I am making.
Per your edited question .. you can achieve this using a stored procedure like below [A sample code]
DELIMITER $$
create procedure sp_insert_update_word(IN CONTENT_DATA VARCHAR(255),
IN FREQ INT, OUT Insert_Id INT)
as
begin
declare #rec_count int;
select #rec_count = count(*) from WORD where content = CONTENT_DATA;
IF(#rec_count > 0) THEN
UPDATE WORD SET FREQUENCY = FREQUENCY + 1 where CONTENT = CONTENT_DATA;
SELECT NULL INTO Insert_Id;
else
INSERT INTO WORD(CONTENT, FREQUENCY) VALUES(CONTENT_DATA, FREQ);
SELECT LAST_INSERT_ID() INTO Insert_Id;
END IF;
END$$
DELIMITER ;
Then call your procedure and select the returned inserted id like below
CALL sp_insert_update_word('some_content_data', 3, #Insert_Id);
SELECT #Insert_Id;
The above procedure code essentially just checking that, if the same content already exists then perform an UPDATE otherwise perform an INSERT. Finally return the newly generated auto increment ID if it's insert else return null.
First try to update frequency where content = "your submitted data here". If the affected row = 0 then insert a new row. You also might want make CONTENT unique considering it will always stored different data.