SQL Set IDENTITY Field Using Variable - sql-server-2008

All, I want to start the numbering of an IDENTITY field based on the current maximum obtained from another table. So I have tried something like the following
DECLARE #CurrentES INT;
SET #CurrentES = (SELECT MaxES
FROM [NDB]..[TmpMaxES]) + 1;
ALTER TABLE BA
ADD ES INT IDENTITY(#CurrentES, 1);
But this will not accept a variable as the seed value in IDENTITY. How can what I require be achieved?
Thanks for your time.

Do do this and other non-variable allowed tasks, you can use the EXEC function, as follows:
DECLARE #CurrentES INT;
SET #CurrentES = (SELECT MaxES
FROM [NDB]..[TmpMaxES]) + 1;
DECLARE #Statement VARCHAR(200)
SET #Statement = 'ALTER TABLE BA
ADD ES INT IDENTITY(' + CAST(#CurrentES AS VARCHAR) + ', 1);'
EXEC (#Statement)

You could use the dbcc checkident feature of SQL Server...
DECLARE #MAXID INT
SELECT #MAXID = MAX(ID_FIELD) FROM OLDTABLE
dbcc checkident(NEWTABLE, reseed, #MAXID)
One thing to note with this is that the value in the 3rd parameter (in this case the #MAXID variable) denotes the current identity value - in other words the last identity value that was generated on the table.
So, for example, if you want the next value that is automatically created to be 100, then set the 3rd parameter to 99.

--first variable
declare #code varchar(50);
set #code=1345688867567576;
--second variable
declare #namedb varchar(50);
set #namedb='test';
--let's you add to the identity(ID) field
SET IDENTITY_INSERT dbo.nameAndroid ON
--declaring variable to hold the next id number
declare #id int;
set #id=##IDENTITY +1;
--clause to check if the table has the matching barcode
if not exists (select * from dbo.nameAndroid where barcode = #code)
INSERT INTO dbo.nameAndroid (id, name, barcode, [floor], Column1,Column2,Row1,Row2,Shelf,Stock,OnOrder)
VALUES ( #id,#namedb, #code, 'Value3', 'Value4','Value5','Value6','Value7','Value8',123,600);
SET IDENTITY_INSERT dbo.nameAndroid OFF;
OR (if the id column is of type int)
declare #code varchar(50);
set #code='123211';
declare #namedb varchar(50);
set #namedb='test';
declare #floordb varchar(50);
set #floordb='test';
declare #Column1db varchar(50);
set #Column1db='test';
declare #Column2db varchar(50);
set #Column2db='test';
declare #Row1db varchar(50);
set #Row1db='test';
declare #Row2db varchar(50);
set #Row2db='test';
declare #Shelfdb varchar(50);
set #Shelfdb='test';
declare #OnOrderdb decimal(18,2);
set #OnOrderdb=10010;
declare #Stockdb decimal(18,2);
set #Stockdb=1010101;
declare #id int;
set #id=((select max(id) from dbo.nameAndroid )+1);
if not exists (select * from dbo.nameAndroid where barcode = #code)
begin
SET IDENTITY_INSERT dbo.nameAndroid ON;
INSERT INTO dbo.nameAndroid (id, name, barcode, [floor], Column1,Column2,Row1,Row2,Shelf,Stock,OnOrder)
VALUES (#id, #namedb, #code, #floordb, #Column1db,#Column2db,#Row1db,#Row2db,#Shelfdb,#OnOrderdb,#Stockdb);
SET IDENTITY_INSERT dbo.nameAndroid OFF;
end

Try something like this..
SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ... (MAX) Value from another table and other applicable record.
...
SET IDENTITY_INSERT [MyTable] OFF

Related

sql trigger unable to set variable from select

I know its asked question ,however I have tried few amendments but to no solution .
My trigger:
BEGIN
DECLARE bookid INT;
DECLARE roomtype varchar(20);
DECLARE amount INT;
DECLARE m_count INT;
DECLARE curr_m varchar(20);
SET #bookid := NEW.id;
SET roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid);
SET amount := (SELECT amount from pm_booking_payment WHERE id_booking=#bookid);
SET #curr_m:= (MONTHNAME(NOW()));
SET #m_count:= (SELECT count(*) FROM pm_report WHERE month=#curr_m);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(#curr_m,#roomtype,#amount);
END
whwn I check table, it inserts, but only #curr which is month name. Rest it inserts NULL
I tried
SET #roomtype SELECT title FROM pm_booking_room WHERE id_booking=#bookid but still same,NULL .
Also tried SET #roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid); but still NULL.
I am using PhpMyadmin to create :
Please help.
Please be aware that roomtype and #roomtype are two different variables.
The variables you declare with the local variable DECLARE statement have a scope within the body of one stored routine. They are never spelled with a # sigil.
The user-defined variables with the # sigil have a scope of a MySQL session. You don't need to declare these kinds of variables. Just setting the variable to a value implicitly creates the variable.
You cannot SET roomtype = ... and expect that string to be read from the #roomtype variable. Nor vice-versa.
You appear to declare local variables, so you should use them consistently. But in some cases, your variable names are the same as column names, which will result in ambiguity if you use the variables in SQL statements that also reference tables with those columns. So you should adopt a naming convention to keep them distinct.
BEGIN
DECLARE v_bookid INT;
DECLARE v_roomtype varchar(20);
DECLARE v_amount INT;
DECLARE v_count INT;
DECLARE v_month varchar(20);
SET v_bookid := NEW.id;
SET v_roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=v_bookid);
SET v_amount := (SELECT amount from pm_booking_payment WHERE id_booking=v_bookid);
SET v_month:= (MONTHNAME(NOW()));
SET v_count:= (SELECT count(*) FROM pm_report WHERE month=v_month);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(v_month,v_roomtype,v_amount);
END
(This code is not tested, so apologies if there are any mistakes. It is meant only to demonstrate using non-sigil variables consistently.)

PHP like $$var in T-SQL (SQL Server 2008)

Is there any way to execute something like php $$var ..?
Which will make the value of a var as var name.
I have been googling for many hours ant cant find any that satisfy my needs.
Thanks.
edit:
currently what I want to achieve is something similar to this
declare #table1 table(Name Varchar(100))
declare #table2 table(Name Varchar(100))
...
declare #table10 table(Name Varchar(100))
declare #int1 int
set #int1 = 0
while #int1 < 10
begin
select #[table + #int1]
END
Since the example in the question isn't valid T-SQL, it's not clear whether you want to select the value of #[table + #int1], or from the table (i.e. select name from #[table + #int1]) - I'm assuming here that it's the second one.
One approach would be to have a single table with an indicator column classifying the rows:
declare #table table(Name Varchar(100), groupid int)
...
declare #int1 int
set #int1 = 0
while #int1 < 10
begin
select name from #table WHERE groupid = #int1
set #int1 = #int1 + 1
end

OUTPUT TO MULTIPLE FILES FROM A SINGLE QUERY

I am a little stuck... I am trying to take the output from a query and break it into numerous files based on a single criteria. I am getting an error of converting a varchar type to int and I cannot figure out why. Working in SQL Server 2008...
DECLARE #LOOP AS INT;
DECLARE #SQL AS VARCHAR(MAX);
DECLARE #BCP AS VARCHAR(MAX);
DECLARE #COUNTER AS INT;
DECLARE #FILENAME AS VARCHAR(MAX);
SET #COUNTER='1'
SELECT #LOOP = COUNT(DISTINCT LIST_ID) FROM DATA_TABLE
WHERE STATUS='2' AND LIST_ID IS NOT NULL ;
SET #SQL=(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B
WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS='2' AND LIST_ID='+#LOOP+');
SET #FILENAME='QUERYOUT C:\Projects\FILE_"'+#LOOP+'.TXT'
WHILE #COUNTER<=#LOOP
BEGIN
SELECT
#BCP='BCP "'+#SQL+'+'+#FILENAME+''
SET #COUNTER=#COUNTER+1
END
GO
The error I am getting is:
Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the varchar value '+#LOOP+' to data type int.
I am trying to use the LOOP value to let me know the contents of each file. For example, LOOP='1' would mean the file contains the customer records associate with LIST_ID='1'
Thoughts on the error?
I'm not sure I understand exactly what you need but if you want to issue the BCP command for every LIST_ID you need to loop though them and execute for each one.
This may not be what you need but rather than wait until I am home from work I will post it now.
DECLARE #FILENAME AS VARCHAR(MAX);
DECLARE #LISTID INT
DECLARE #LOOP AS INT;
DECLARE #BCP AS VARCHAR(MAX);
DECLARE #SQL AS VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT DISTINCT LIST_ID FROM DATA_TABLE WHERE STATUS='2' AND LIST_ID IS NOT NULL
OPEN cur
FETCH NEXT FROM cur INTO #LISTID
WHILE ##FETCH_STATUS = 0 BEGIN
SET #FILENAME='QUERYOUT C:\Projects\FILE_'+Cast(#LISTID AS Varchar)+'.TXT -c -t -T'
SET #SQL='(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+#LISTID+')';
SELECT #BCP='BCP '+#SQL+' '+#FILENAME+''
EXEC xp_cmdshell #BCP
FETCH NEXT FROM cur INTO #LISTID
END
CLOSE cur
DEALLOCATE cur
1.change varchar(max) to varchar(8000)
2.Add DBNAME.SCHEMA for all the tables, because by default it will point to the Master db.
Added double quotes(") below
3. #FILENAME='QUERYOUT "C:\Projects\FILE_'+Cast(#LISTID AS Varchar)+'.TXT" -c -t -T'
4. '("SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+#LISTID+'")';

How to call trigger while inserting a data

my table structure is like itemcode, size , sleeve ,item .so people inserting data like 'S0001','F','96' at the time of inserting i need to insert item field data like 'S0001-f-96' how do i write a trigger .
create TRIGGER [dbo].[name] ON [dbo].[table]
for INSERT
AS
declare #Itemcode varchar(30);
declare #Itemname varchar(40);
declare #Slv varchar(1);
declare #Createdate datetime;
declare #audit_action varchar(100);
select #Itemcode=i.ItemCode from inserted i;
select #Itemname=i.ItemName from inserted i;
select #Slv =i.U_SLV from inserted i;
select #Createdate =i.Createdate from inserted i;
set #audit_action='Inserted Record -- After Insert Trigger.';
update OITM_CLONE set sapitem =#Itemcode+'-'+#Slv where itemcode=#Itemcode and u_slv=#Slv and Createdate=#Createdate;
PRINT 'AFTER INSERT trigger fired.'
is this right?

How to update/Edit table through CSVs?

I stored 2 contact numbers in a table corresponding to one companyID in companycontactno. table. I did that using extracting values from CSV in Stored procedure.
If I want to edit those contact numbers Corresponding to company ID how am I going to do that?
This is the storedProcedure I will use for editing contact numbers .. I am having difficulty in updating it .. please help
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE PROCEDURE dbo.EditCompanyDetails
(
#OldCompanyName varchar(max),
#NewCompanyName varchar(max),
#newAddress varchar(max),
#newMailID varchar(max),
#Temp varchar(8000)
)
AS
BEGIN
SET NOCOUNT ON;
declare #compID int
DECLARE #c int, #a varchar(max), #id int, #variable varchar(8000), #max int
DECLARE #Temp_Table table (serial_no int Identity(1,1), value varchar(max))
--PROCEDURE--
--Editing Company Table--
set #compID=(Select Company.CompanyID from Company where Company.CompanyName=#OldCompanyName)
update Company
set CompanyName=#NewCompanyName, [Address]=#newAddress, Email=#newMailID
where Company.CompanyID=#compID
--For CONTACT NUMBERS
--Using Table to store CSV seperately in each row--
select #c = CHARINDEX(',', #Temp)
while #c > 0
BEGIN
insert into #Temp_Table
select LEFT(#Temp, #c - 1)
select #Temp = right(#Temp, LEN(#Temp) - #c)
select #c = CHARINDEX(',', #Temp)
END
--Update Table CompanyContactNo
--CompanyContactNo have following Columns:
--CNoID (PK)
--CompanyID (references PK in Company table
--ContactNumber
set #max= (select MAX(serial_no) from #Temp_Table)
while #max > 0
BEGIN
set #variable = (select value from #Temp_Table where serial_no=#max)
update CompanyContactNo
set ContactNumber=#variable
where CompanyID=#compID
set #max = #max-1
END
End
GO
Assuming you will only have 2 rows, and you know that there are 2 contact rows in the CompanyContactNo table, you could execute 2 Update statements that would each affect a different row:
UPDATE CompanyContactNo
Set ContactNumber=
(SELECT value FROM #Temp_Table WHERE serial_no = (SELECT MAX(serial_no) FROM #Temp_Table))
WHERE
CompanyID=#compID
AND (CNoId = select MAX(CNoId) FROM CompanyContactNo WHERE CompanyID = #compID)
and then for second contact number:
UPDATE CompanyContactNo
SET ContactNumber=
(SELECT value FROM #Temp_Table WHERE serial_no = (SELECT MIN(serial_no) FROM #Temp_Table))
WHERE
CompanyID=#compID
AND (CNoId = select MIN(CNoId) FROM CompanyContactNo WHERE CompanyID = #compID)