PHP like $$var in T-SQL (SQL Server 2008) - 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

Related

MySQL stored procedure issue, generate custom ID's

I had a stored procedure for making custom ID, but it was for SQL Server and I tried to convert it to MySQL with help of an online tool, and I get errors and I need help from you guys :(
This stored procedure will produce ID codes for my users, like for admin (AD001, AD002,...etc), first, it will look if there is no value it will generate the first value like (AD001) if there is a value it will get the value and increment it by 1.
This is my SQL Server version of the procedure which works:
create procedure admin_code
as
begin
declare #max int, #no varchar(50), #value varchar(50)
select #max = isnull(max(cast(right(id_user, 3) as int)), 0) + 1
from admin_information
if #max < 100
select #no = 'AD' + right('00000' + cast(#max as varchar(50)), 3)
else if #max >= 100
select #no = 'AD' + right('0' + cast(#max as varchar(50)), 4)
if #max >= 1000
select #no = 'AD' + right('0' + cast(#max as varchar(50)), 5)
print #no
select #no
return 0
end
And this is for MySQL
create procedure admin_code()
sp_lbl:
begin
declare v_max int;
declare no varchar(50);
declare value varchar(50);
select v_max=ISNULL( max(cast(RIGHT(id_user,3)as int)),0)+1 into v_max from admin_information;
if v_max <100 then
set v_no=CONCAT('AD',RIGHT('00000'+CAST(v_max as varchar(50)),3));
elseif
v_max>=100 then
-- SQLINES LICENSE FOR EVALUATION USE ONLY
set v_no=CONCAT('AD',RIGHT('0'+CAST(v_max as varchar(50)),4));
end if;
if v_max>=1000 then
-- SQLINES LICENSE FOR EVALUATION USE ONLY
set v_no=CONCAT('AD',RIGHT('0'+CAST(v_max as varchar(50)),5))
print;
end if; v_no
-- SQLINES LICENSE FOR EVALUATION USE ONLY
select v_no;
LEAVE sp_lbl 0;
end;
This is the online tool I used:
http://www.sqlines.com/online
Error:

Select UNION from multiple tables via variable

I have a query that selects from multiple tables using a join. I want to execute this query from different databases via a loop.
I have accomplished that via (simplified query):
DECLARE #intCounter int
SET #intCounter = 1
DECLARE #tblBedrijven TABLE (ID int identity(1,1),
CompanyName varchar(20),
DatabaseTable varchar(100))
INSERT INTO #tblBedrijven VALUES ('001-CureCare', '<TABLE/ DATABASE1> AUS'),
('002-Cleaning', '[global_nav5_prod].[dbo].<TABLE/ DATABASE2>] AUS')
DECLARE #strCompany varchar(20)
DECLARE #strTable varchar(100)
WHILE (#intCounter <= (SELECT MAX(ID) FROM #tblBedrijven))
BEGIN
SET #strTable = (SELECT DatabaseTable FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strCompany = (SELECT CompanyName FROM #tblBedrijven
WHERE ID = #intCounter)
EXEC('SELECT ''' + #strCompany + ''' as Company,
AUS.[User],
AUS.[E-mail]
FROM' + #strTable)
SET #intCounter = #intCounter + 1
END
My problem is that the result generates 2 separate tables (for every loop). I want to union the results but have no clue how.
Any suggestions?
Thanks in advance.
Can't you use something like the below code where you append all the sqls with union and finally execute the sql once only without executing in a loop. I am not an expert in SQL Server but I have written many other similar stored procedures using other RDBMS. So please bear any syntax errors.
DECLARE #intCounter int
DECLARE #maxId int
SET #intCounter = 1
DECLARE #tblBedrijven TABLE (ID int identity(1,1),
CompanyName varchar(20),
DatabaseTable varchar(100))
INSERT INTO #tblBedrijven VALUES ('001-CureCare', '<TABLE/ DATABASE1> AUS'),
('002-Cleaning', '[global_nav5_prod].[dbo].<TABLE/ DATABASE2>] AUS')
DECLARE #strCompany varchar(20)
DECLARE #strTable varchar(100)
DECLARE #strSql varchar(5000)
SET #maxId = (SELECT MAX(ID) FROM #tblBedrijven)
WHILE (#intCounter <= #maxId)
BEGIN
SET #strTable = (SELECT DatabaseTable FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strCompany = (SELECT CompanyName FROM #tblBedrijven
WHERE ID = #intCounter)
SET #strSql = #strSql + ('SELECT ''' + #strCompany + ''' as Company,
AUS.[User],
AUS.[E-mail]
FROM' + #strTable)
IF #intCounter < #maxId THEN
BEGIN
SET #strSql = #strSql + ' UNION '
END
SET #intCounter = #intCounter + 1
END
EXEC(#strSql)

Shuffle a string with mysql/sql

I was wondering, if there is some way to shuffle the letters of a string in mysql/sql, i.e. something like the pseudocode: SELECT SHUFFLE('abcdef')?
Couldn't find any from http://dev.mysql.com/doc/refman/5.0/en/string-functions.html and searching for it just seems to find solutions for shuffling results, not a string.
Here you go:
DELIMITER //
DROP FUNCTION IF EXISTS shuffle //
CREATE FUNCTION shuffle(
v_chars TEXT
)
RETURNS TEXT
NOT DETERMINISTIC -- multiple RAND()'s
NO SQL
SQL SECURITY INVOKER
COMMENT ''
BEGIN
DECLARE v_retval TEXT DEFAULT '';
DECLARE u_pos INT UNSIGNED;
DECLARE u INT UNSIGNED;
SET u = LENGTH(v_chars);
WHILE u > 0
DO
SET u_pos = 1 + FLOOR(RAND() * u);
SET v_retval = CONCAT(v_retval, MID(v_chars, u_pos, 1));
SET v_chars = CONCAT(LEFT(v_chars, u_pos - 1), MID(v_chars, u_pos + 1, u));
SET u = u - 1;
END WHILE;
RETURN v_retval;
END;
//
DELIMITER ;
SELECT shuffle('abcdef');
See sqlfiddle.com for the output.
Tested successfully with mariadb 10.1 (mysql 5.6 equivalent)
Edit: this solution is for Microsoft SQL Server.
As it's not allowed to use RAND() in user defined function, we create a view to use it later in our shuffle function:
CREATE VIEW randomView
AS
SELECT RAND() randomResult
GO
The actual shuffle function is as following:
CREATE FUNCTION shuffle(#string NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) AS
BEGIN
DECLARE #pos INT
DECLARE #char CHAR(1)
DECLARE #shuffeld NVARCHAR(MAX)
DECLARE #random DECIMAL(18,18)
WHILE LEN(#string) > 0
BEGIN
SELECT #random = randomResult FROM randomView
SET #pos = (CONVERT(INT, #random*1000000) % LEN(#string)) + 1
SET #char = SUBSTRING(#string, #pos, 1)
SET #shuffeld = CONCAT(#shuffeld, #char)
SET #string = CONCAT(SUBSTRING(#string, 1, #pos-1), SUBSTRING(#string, #pos+1, LEN(#string)))
END
RETURN #shuffeld
END
Calling the function
DECLARE #string NVARCHAR(MAX) = 'abcdefghijklmnonpqrstuvwxyz0123456789!"ยง$%&/()='
SELECT dbo.shuffle(#string)
There is nothing in standard SQL - your best bet is probably to write a user defined function

MySQL INSERT WHERE a variable is not duplicated

I have some troubles with DECLARE, CALL function and a IF settelment. What i have so far is:
CREATE PROCEDURE number_of_projects(project_name VARCHAR)
BEGIN
DECLARE variable INT;
SET variable = 4;
SELECT variable;
SELECT count(project_id) FROM atm_projects WHERE project_name = variable;
END
IF number_of_projects("PROJECT NAME") = 0
THEN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
VALUES (project_id,'PROJECT NAME',1)
ENDIF
The main goal is to insert a row into a table where project_name is not duplicated.
I could change project_name to an UNIQUE key but please tell me what is wrong with my code, an how can i fix this?
I need to learn how a PROCEDURE, CALL procedure, IF works.
try:
CREATE PROCEDURE number_of_projects(project_name VARCHAR(255))
BEGIN
DECLARE var_project_no INT;
SET var_project_no = 0;
SELECT var_project_no;
SELECT count(project_id) INTO var_project_no FROM atm_projects WHERE var_project_name = 4;
IF var_project_no = 0
THEN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
VALUES (project_id,'PROJECT NAME',1)
END IF;
END;
You have declared project_name to varchar without specifying the length. Change it to varchar(100)
CREATE PROCEDURE number_of_projects(project_name VARCHAR(255))
BEGIN
if NOT exists(SELECT Top 1 1 FROM atm_projects WHERE var_project_name = 4)
BEGIN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
Select project_id,project_name ,1
END
END;

SQL Set IDENTITY Field Using Variable

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