By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,482 Members | 3,157 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

MySQL to MS SQL Conversion

ssnaik84
100+
P: 149
Hi Guys,

Last year I got a chance to work with R&D team, which was working on DB scripts conversion..
Though there is migration tool available, it converts only tables and constraints..
Rest of things (stored procedures, functions).. we have to manually edit.
That time, we face some interesting challenges.. I failed to document all of them, but whatever I can share with u.. I will try.. :)


=================================================

Index
-------------------------------------------------------
1. MySQL Variables
-- user variables (Global Variables)
-- local variables

2. Migration Hints
How to get
-- last inserted identity value
-- current date and time
-- declare a dummy table

3. MySQL String Functions
-- CONCAT
-- CONCAT_WS
-- GROUP_CONCAT

4. UNIQUEIDENTIFIER

5. How to return (exit) from SP conditionally?

6. How to execute Dynamic SQL in stored procedure?

7. MySQL Cursor


=================================================

1. MySQL Variables

In MySQL, there are 2 types of variables:

user variables: (Global Variables)
- symbol “@” is used to designate them.
- User variable is a variable, is working during the whole connection to the database.
- All variables for a given client connection are automatically freed when that client exits.
- User-defined variables are connection-specific. That is, a user variable defined by one client cannot be seen or used by other clients
- User variable names not case sensitive in MySQL 5.0 and up.
- Syntax: SET @var_name = expr [, @var_name = expr] …
- Example: SET @t1=0, @t2=0, @t3=0;
- Note: You can also assign a value to a user variable in statements other than SET.
In this case, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements
e.g.
Expand|Select|Wrap|Line Numbers
  1. SET @t1=1, @t2=2, @t3=3;
  2. SELECT @t1,@t2,@t3; ==> output: 1,2,3
  3. SELECT @t1:=8,@t2,@t3; ==> output: 8,2,3
  4.  
local variables: (Recommended in Stored Procedure)
- The DECLARE statement is used to declare local variables.
- local variable works only within a procedure body.
- DECLARE may only be used inside a BEGIN … END compound statement and must be at its start, before any other statements.
- The scope of a variable is within the BEGIN … END block.
- Syntax: DECLARE var_name [, var_name] … type [DEFAULT value]
- Example: DECLARE l_TagID INT DEFAULT 0;
- Note: If the DEFAULT clause is missing, the initial value is NULL.

How to use local variables in MySQL:
————————————-
To change Microsoft SQL Sever local variable name (@var) to MySQL local variable name, replace symbol “@” with “v_”. (select all, replace all)

Example: @userID ==> v_userID

————————————-
Expand|Select|Wrap|Line Numbers
  1. MS-SQL:
  2. DECLARE @uname, @addr VARCHAR(200);
  3. SELECT @uname = uname, @addr = address FROM tbluser WHERE uid = @uid;
  4.  
  5. MySQL:
  6. DECLARE v_uname, v_addr VARCHAR(200);
  7. SELECT uname, address INTO v_uname, v_addr tbluser FROM tbluser WHERE uid = v_uid;
————————————-

Example:
Expand|Select|Wrap|Line Numbers
  1. DELIMITER $$
  2. DROP PROCEDURE IF EXISTS `mytest`$$
  3. CREATE PROCEDURE `mytest`
  4. (
  5. IN v_id INT
  6. )
  7. BEGIN
  8. create temporary table temp
  9. (
  10. id int primary key auto_increment ,
  11. val int
  12. );
  13. insert into temp (val) values (22);
  14. insert into temp (val) values (50);
  15. insert into temp (id, val) values (99, 80);
  16. insert into temp (val) values (9000);
  17. begin
  18. declare v_val int default 0;
  19. select id, val into v_id, v_val from temp where id=v_id;
  20. select v_id, v_val;
  21. end;
  22. – select v_id, v_val;
  23. – (If you try to display local variables outof their scope (begin.. end), you will get error: Unknown column ‘v_val’ in ‘field list’)
  24. drop temporary table temp;
  25. END$$
  26. DELIMITER ;
  27.  
  28. try to run it with: call mytest(100)

=================================================

2. Migration Hints


@@IDENTITY is also available in MySQL.

SELECT @@IDENTITY AS ‘Identity’;

it returns last inserted identity value.
But, better to use LAST_INSERT_ID()

—————————————–
How to update a table from other

Expand|Select|Wrap|Line Numbers
  1. UPDATE JOIN …..
  2. ON . = .
  3. SET . =
  4. WHERE
—————————————–

MS-SQL: GetDate() ==> Use sysdate() , SELECT CURRENT_TIMESTAMP;

—————————————–

You are allowed to specify DUAL as a dummy table name in situations where no tables are referenced
Expand|Select|Wrap|Line Numbers
  1. SELECT 1 FROM dual
  2. WHERE left(@sSQL,2) in ('v_','d_','e_','f_','g_','h_','i_','j_')
  3.  

=================================================

3. MySQL String Functions



CONCAT function:

———————
- Always use CONCAT for concatenation (to replace “+” operator in MS-SQL).
- Avoid “||” (double pipe)
- Take care of NULL value with IFNULL(column_name, ”); before concatenation, Otherwise, it’ll return null.

Example:
Expand|Select|Wrap|Line Numbers
  1. DELIMITER $$
  2. DROP PROCEDURE IF EXISTS `mytest`$$
  3. CREATE PROCEDURE `mytest`()
  4. BEGIN
  5. declare v_str1, v_str2, v_str3, v_str4 varchar(20);
  6. declare v_res varchar(100);
  7. set v_str1 = “abc”;
  8. set v_str2 = “pqr”;
  9. set v_str3 = “xyz”;
  10. set v_str4 = “123″;
  11. set v_res = concat(v_str1,v_str2,v_str3, v_str4); — , null);
  12. select v_res;
  13. END$$
  14. DELIMITER ;
  15. RUN: call mytest();
  16.  
CONCAT_WS function:
————————————

- for Concatenate With Separator and is a special form of CONCAT().
The first argument is the separator for the rest of the arguments.
The separator is added between the strings to be concatenated

- Advantage over CONCAT: need not to check IFNULL values of each column.
It takes cares of it internally.
- Note: If the separator is NULL, the result is NULL.

Syntax: CONCAT_WS(separator,str1,str2,…);

Example:
Expand|Select|Wrap|Line Numbers
  1. SELECT CONCAT_WS(’,’,’First name’,’Second name’,null,’Last Name’);
  2. -> ‘First name,Second name,Last Name’
GROUP_CONCAT Function:
———————————————
-This function returns a string result with the concatenated non-NULL values from a group.
- USE: To concatenate multiple MySQL rows into one field

Example:
————-
Expand|Select|Wrap|Line Numbers
  1. if
  2. select col_name from temp_table;
  3. ==>
  4. col_name
  5. ———-
  6. ‘abc’
  7. ‘xyz’
  8. ‘pqr’
  9.  
  10. declare v_str varchar(100);
  11. select group_concat( col_name separator ‘*’) into v_str from temp_table;
  12. select v_str;
  13.  
  14. output: ‘abc*xyz*pqr’
  15.  
  16.  

Why to avoid “||” double pipe for concatenation
——————————————————–

double pipe can be used for concatenation, but, it is only legal while the sql mode is ansi.

You can tell mysqld to run in ANSI mode with the –ansi startup option.
mysqld –transaction-isolation=SERIALIZABLE –sql-mode=ANSI
or,
SET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET GLOBAL sql_mode = ‘ANSI’;

=================================================

4. How to replace UNIQUEIDENTIFIER

UNIQUEIDENTIFIER is not a data type in MySQL.
We can use VARCHAR(50), as both generate GUID.

MS-SQL:
——————-
NEWID()
output: D747AE09-5E4C-44BB-BCAE-DD40EDD7747B

MySQL :
——————-
UUID()
output: 28c93603-0752-102c-ab9e-93e0a9ae6d17

Example:
————————————–
Expand|Select|Wrap|Line Numbers
  1. DELIMITER $$
  2. DROP PROCEDURE IF EXISTS `mytest`$$
  3. CREATE PROCEDURE `mytest`()
  4. BEGIN
  5. DECLARE id VARCHAR(50);
  6. SET id = UUID();
  7. SELECT id;
  8. END$$
  9. DELIMITER ;
  10. run it with: call mytest()
  11.  
=================================================

5. How to return (exit) from SP conditionally?
—————————————————
There is no alternative keyword for “return” in SP of MS-SQL.
Use “LEAVE” instead.
Put extra BEGIN & END with a label (say main)
It’s also used, for exiting through a loop.

Example:
Expand|Select|Wrap|Line Numbers
  1. DELIMITER $$
  2. DROP PROCEDURE IF EXISTS `mytest`$$
  3. CREATE PROCEDURE `mytest`()
  4. BEGIN
  5. MAIN: BEGIN
  6. SELECT ‘HI’;
  7. IF 1=1 THEN
  8. SELECT ‘ABC’;
  9. LEAVE MAIN;
  10. END IF;
  11. SELECT ‘BYE’;
  12. END MAIN;
  13. END$$
  14. DELIMITER ;
  15.  
  16. To Run: call mytest()
  17.  
=================================================

6. How to execute Dynamic SQL in stored procedure

step 1. CONCATE it.
———————————————————-
CONCATE sql strings & store it into User Variable

SET @dynamic_sql = CONCATE(”SELECT * FROM mytable” , ” WHERE userid=”, v_uid);

step 2. PREPARE it.
———————————————————-
To execute dynamic sql, you need to prepare it first.

PREPARE complete_sql FROM @dynamic_sql;

Note: PREPARE statement does not work with local variables (e.g. v_sql).
It is explicitly designed to work with user variables and constant strings only.

step 3. EXECUTE it.
———————————————————-
EXECUTE complete_sql;

step 4. DEALLOCATE it.
———————————————————-
DEALLOCATE the prepared statement.

DEALLOCATE PREPARE complete_sql;


=================================================

7. MySQL Cursor

A cursor has following main steps:

1) DECLARE cursor-name CURSOR FOR SELECT …;
2) OPEN cursor-name;
3) FETCH cursor-name INTO variable [, variable];
4) CLOSE cursor-name;

———————————————————————
Example:
Expand|Select|Wrap|Line Numbers
  1. DELIMITER $$
  2. DROP PROCEDURE IF EXISTS `newTest`$$
  3. CREATE PROCEDURE `newTest`()
  4. BEGIN
  5. create temporary table temp
  6. (
  7. id int primary key auto_increment ,
  8. val int
  9. );
  10. insert into temp (val) values (60);
  11. insert into temp (val) values (60);
  12. insert into temp (id, val) values (99, 80);
  13. insert into temp (val) values (9000);
  14. BEGIN
  15. DECLARE colID, colVAL, handle INT;
  16. DECLARE mycur CURSOR FOR SELECT id, val FROM temp; -- declare cursor
  17. DECLARE CONTINUE HANDLER FOR NOT FOUND SET handle = 1; -- declare handle
  18. OPEN mycur; -- open cursor
  19. FETCH mycur INTO colID, colVAL; -- fetch first row values from cursor
  20. REPEAT
  21. SELECT colID, colVAL; -- your code
  22. FETCH mycur INTO colID, colVAL; -- fetch values from cursor
  23. UNTIL handle = 1
  24. END REPEAT;
  25. CLOSE mycur; -- close cursor
  26. END;
  27. drop temporary table temp;
  28. END$$
  29. DELIMITER ;
  30.  
  31. call newTest();
  32.  
Oct 11 '09 #1
Share this Article
Share on Google+
1 Comment


100+
P: 201
not to get off topic, better choice is mysql server!
Nov 11 '09 #2