Get values based on newly inserted value using SQL - sql

I want to make filtration on a column after selecting a specific value of another column in the same table, I tried to use #... special character followed by the column's name to get the address of this value.
My SQL statement is like the following :
SELECT ATTRIBUTE FROM TABLE WHERE FIELD = '#FIELDNAME';
If I used a specific value instead of #FIELDNAME, it will work properly but it will be static but I need it to be dynamic based on the selected value.

Create another table which will have the list of values that are in the FIELDNAME and give each record a unique id ,then retrieve the value depending on what you have selected by the name of the new table's field preceded by '#...'
I don't know if that what are you looking for, please let me know.

If no triggers are allowed, do you have any date/time column in the table? Is it possible to have that extra column anyway to see the time of a newly inserted row?
You may have to check the lastest row entered, save its field value into a variable. Then do the select based on the variable value.
Based on the vague last row id you could try the following (it's not pretty). But again, if you have date/time that's more accurate.
select attribute from table
where field = (select field from table
where rowid =(select max(rowid) from table))
;
upate
Do you have the priviledge to set up your insert command as below:
insert into table (id, col1, col2,...) values (1,'something', 'something',...)
returning id into variable; -- you may either save field or id depending on your table
Then you may use this variable to select the records you want.

Related

SQL - replace all column values with 'X' the same length

I am trying to create a stored procedure that replaces all values in one column with Xs the same length as the original values. Here is what I have so far:
SELECT REPLICATE('x', LEN(Name))
This code shows the output with Xs but it does not make this change permanently in the database. Is there a way to make this change permanently in the database?
You need to use an UPDATE statement to physically modify the record:
Update YourTable
Set Name = Replicate('x', Len(Name))
However, I would caution that this will update EVERY record in your table to just XXXX.... You will be effectively removing/destroying all data in that column.
Please do not run this statement unless you are absolutely certain this is what you intend to do.
If your goal actually is to remove all data from that column for every record, and your field is nullable, you could save some space by doing:
Update YourTable
Set Name = Null

How to generate auto generated sequence no in sql

I have one requirement. I already have a table named WorkOrder. In this table there is a column Named WorkorderId set as primary key and identity. The next one is voucherNumber. Now I want to generate voucherNumber automatically. The condition is voucher number will not repeat. E.g., first I insert 2 rows into the table and after that I delete the 2nd entry. The next time my voucher number should be 3. Again i insert 3 more entries then after that my voucher no should be 6. Then i delete one row from this table after that my voucher number should be 7. If i delete the last row (I mean 7) then next time the voucher number should the same.
Use IDENTITY(...) when creating the column. This will make a field auto-increment its value.
You'll have to drop the column first in case that it already exists. There is no (clean) way to make this happen on already existing columns.
For further information and examples you can check out http://www.w3schools.com/sql/sql_autoincrement.asp
Edit: Sorry, I have overlooked the info that you are already using IDENTITY(...) on the PK column. Unfortunately SQL-Server can only have a single column with the IDENTITY property per table... So in this case you'll have to make use of a trigger.
This is an example:
CREATE TRIGGER CountRows
ON TestCount
AFTER UPDATE
AS
UPDATE TestCount SET Cnt = Cnt +1 WHERE ID IN (SELECT ID from inserted)
GO
In case you want to enter an IDENTIFIER to the record, it is best to use uniqueIdentifier type column. It is a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.
On insertion, you can simply proceed as follows;
Insert into MyTable
(WorkorderId, WorkName) values (NewId(), 'Test')
Using this, you can be sure the Id is globally unique.

Sql Server - How to get last id inserted into table

I'm trying to get the last id inserted into a table.
I was using
SELECT IDENT_CURRENT('TABLE')
But the problem is that it doesn't return the last inserted id, it returns the max inserted id.
For example, if i do:
INSERT INTO 'TABLA' (ID) VALUES (100)
SELECT IDENT_CURRENT('TABLE') returns 100
but then if i do
INSERT INTO 'TABLA' (ID) VALUES (50)
SELECT IDENT_CURRENT('TABLE') returns 100
and I want to get 50
I need the ID of a specific table, and I generate the id dinamically, so it's not an identity
How can i do it?
From your code, it looks like ID is not an identity (auto-increment) column, so IDENT_CURRENT isn't going to do what you are expecting.
If you want to find the last row inserted, you will need a datetime column that represents the insert time, and then you can do something like:
SELECT TOP 1 [ID] FROM TABLEA ORDER BY [InsertedDate] DESC
Edited: a few additional notes:
Your InsertedDate column should have a default set to GetDate() unless your application, stored procs or whatever you use to perform inserts will be responsible for setting the value
The reason I said your ID is not an identity/auto-increment is because you are inserting a value into it. This is only possible if you turn identity insert off.
SQL Server does not keep track of the last value inserted into an IDENTITY column, particularly when you use SET IDENTITY_INSERT ON;. But if you are manually specifying the value you are inserting, you don't need SQL Server to tell you what it is. You already know what it is, because you just specified it explicitly in the INSERT statement.
If you can't get your code to keep track of the value it just inserted, and can't change the table to have a DateInserted column with a default of CURRENT_TIMESTAMP (which would allow you to see which row was inserted last), perhaps you could add a trigger to the table that logs all inserts.
SELECT SCOPE_IDENTITY()
will return the last value inserted in current session.
Edit
Then what you are doing is the best way to go just make sure that the ID Column is an IDENTITY Column, IDENT_CURRENT('Table_name'), ##IDENTITY and SCOPE_IDENTITY() returns last value generated by the Identity column.
If the ID column is not an Identity Column, all of these functions will return NULL.

SQL insert row with one change

I have this table:
Table1:
id text
1 lala
And i want take first row and copy it, but the id 1 change to 2.
Can you help me with this problem?
A SQL table has no concept of "first" row. You can however select a row based on its characteristics. So, the following would work:
insert into Table1(id, text)
select 2, text
from Table1
where id = 1;
As another note, when creating the table, you can have the id column be auto-incremented. The syntax varies from database to database. If id were auto-incremented, then you could just do:
insert into Table1(text)
select text
from Table1
where id = 1;
And you would be confident that the new row would have a unique id.
Kate - Gordon's answer is technically correct. However, I would like to know more about why you want to do this.
If you're intent is to have the field increment with the insertion of each new row, manually setting the id column value isn't a great idea - it becomes very easy for there to be a conflict with two rows attempting to use the same id at the same time.
I would recommend using an IDENTITY field for this (MS SQL Server -- use an AUTO_INCREMENT field in MySQL). You could then do the insert as follows:
INSERT INTO Table1 (text)
SELECT text
FROM Table1
WHERE id = 1
SQL Server would automatically assign a new, unique value to the id field.

sql - retain calculated result in calculated field

certain fields in our database contain calculated functions e.g.
select lastname + ', ' + firstname as fullname from contact where contact.id =$contact$
when viewing the field the correct data is shown (i assume this is because when you open the record, the calculation is executed). however, the data is not 'stored' to the field, and therefore is null until the record is opened. is it possible to 'store' the result to the field, making it possible to search the data?
many thanks
james
EDIT
it is not possible for me to create computed_columns using our software.
the above field is a text feild where either 1) a user can manual type in the required data or 2) the database can generate the answer for you (but only whilst you are looking at the record). i know that if I run the following:
Select * from contact where contact.id =$contact$ for xml auto
i only get lastname, firstname - so i know that the fullname field does not retain its information.
If you are using computed columns in sql server, the column is already searchable regardless of whether the calculation result is stored or not. However, if you would like to make it so that the calculation is not run each time you read the row, you can change that under row properties in your Modify Table GUI.
Use the PERSISTED key word when you create the column
From BOL:
PERSISTED
Specifies that the SQL Server Database Engine will physically store the computed values in the table, and update the values when any other columns on which the computed column depends are updated. Marking a computed column as PERSISTED lets you create an index on a computed column that is deterministic, but not precise. For more information, see Creating Indexes on Computed Columns. Any computed columns that are used as partitioning columns of a partitioned table must be explicitly marked PERSISTED. computed_column_expression must be deterministic when PERSISTED is specified.
This isn't the way computed columns work in SQL Server, so I suspect this is something your client application is doing. How are you looking at the data when the value is computed correctly? Does it work when you view the data in SSMS?
Take a look at http://msdn.microsoft.com/en-us/library/ms191250(v=SQL.90).aspx to see how to create computed columns properly.
eg.
create table TestTable
(a int,
b int,
c as a + b)
insert into TestTable (a,b)
values (1,2)
select * from TestTable
where c = 3
This query is based on the computed column and it returns the row that's been inserted.
You need to use the PERSISTED option on a column when you use CREATE TABLE e.g.
CREATE TABLE test (col_a INT, col_b INT, col_c AS col_A * col_B PERSISTED)