drop type by variable in MSSQL - sql-server-2008

How can I drop a type by using variable in MSSQL?
I can't drop it in the following way:
create procedure DropSomething(
#tName nvarchar(1000)
, #tCode nvarchar(1000)
)
as
begin
set nocount on
if #tCode = 'type'
begin
if exists(select [name] from sys.types where [name] = #tName)
drop type #tName
end
end
go
exec DropSomething N'typeName','type'
Here is the error message:
Msg 102, Level 15, State 1, Procedure DropSomething, Line 16 [Batch Start Line 19]
The syntax near '#tName' is incorrect.

You can't parameterize identifiers in SQL. Parameters are placeholders for data, and identifiers are not data.
You need to use dynamic SQL:
if #tCode = 'type'
begin
if exists(select [name] from sys.types where [name] = #tName)
begin
declare #sql nvarchar(200) = 'drop type ' + QUOTENAME(#tName)
exec(#sql)
end
end

Related

What is wrong with my mysql stored procedure?

I have a stored procedure that checks whether or not a new entry is already existing in the table. if it exists, the insert will not happen. when I run it, there is an error
DROP PROCEDURE IF EXISTS AddPriority2;
DELIMITER $$
CREATE PROCEDURE AddPriority2
(
IN strName VARCHAR(100),
OUT itExists INT
)
BEGIN
DECLARE
SELECT COUNT(Id) INTO itExists
FROM priorities
WHERE Name = strName AND StatId = 1;
IF(itExists = 0) THEN
INSERT INTO priorities
(
NAME,
StatId
)
VALUES
(
strName,
1
);
END IF;
END
here is the error
Query: CREATE PROCEDURE AddPriority2 ( IN strName VARCHAR(100), OUT itExists INT ) BEGIN DECLARE SELECT COUNT(Id) INTO itExists FROM pr...
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT COUNT(Id) INTO itExists
FROM priorities
WHERE Name = strName AND StatId =' at line 8
1) You cannot declare a select statement - a declare has to be for a variable..(and I would not use an output parameter for that) 2) or you can use exists instead
if not exists (select 1 from priorities WHERE Name = strName AND StatId = 1) then
insert...
end if;

I keep getting an "unexpected character" and an "unrecognized data type" errors when creating a stored procedure in sql

So I am trying to create a stored procedure based off of a code I found online,this is the code:
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Table
VALUES (a, b)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE table
SET Name = #Name, Country = #Country
WHERE CustomerId = #CustomerId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Table
WHERE CustomerId = #CustomerId
END
END
Using this database:
**friend**-->
Content:user_id,friend_id;
**user**-->
Content:user_id,email,password;
**user_extra**-->
Content:user_id,name,surname,birth_date,country_of_birth,user_name;
Now I keep getting an error on line 1:
"Unexpected character.(near[)",
"Unexpected character.(near [)"
and an error on line 2:
"Unrecognized data type.(near))"
now I checked my code and can not find mistakes but I do not know why I keep getting these error can someone care to explain,new to mysql and btw I was using this in the phpmyadmin sql section.
CREATE PROCEDURE SP_Name(IN Action VARCHAR(10))
BEGIN
SET NOCOUNT ON ;
--INSERT
IF (#Action = ‘INSERT’) THEN
BEGIN
INSERT INTO Table
VALUES (a, b)
END
END IF ;
--UPDATE
IF( #Action = ‘UPDATE’) THEN
BEGIN
UPDATE table
SET Name = #Name, Country = #Country
WHERE CustomerId = #CustomerId
END
END IF ;
--DELETE
IF (#Action = ‘DELETE’) THEN
BEGIN
DELETE FROM Table
WHERE CustomerId = #CustomerId
END
END IF ;
END
i think this should work for you
read about how to create procedure syntax here also about how to use the IF statement Syntax in mysqlhere and you might want to check how to declare variables too , because this code should be fine but the NONCOUNT variable is not defined , read about declaring variables here

How to Update values in sql by Muliple Column name in Sql

I want add values to multiple columns
ALTER PROCEDURE DynamicInsertQuery
#ColumnName VARCHAR(MAX),
#RiD VARCHAR(50)
AS
BEGIN
DECLARE #DynamicQuery NVARCHAR(MAX)
SET #DynamicQuery = 'UPDATE tbl_route_info SET ('+ #ColumnName +') = (1) WHERE RouteId=('+#RiD+')'
EXEC(#DynamicQuery)
END
This is the code I tried.
I run this procedure like this
DynamicInsertQuery '(1,2)','10'
I suspect you want something like this:
ALTER PROCEDURE DynamicInsertQuery (
#ColumnName VARCHAR(MAX),
#RiD VARCHAR(50)
) AS
BEGIN
DECLARE #DynamicQuery NVARCHAR(MAX);
SET #DynamicQuery = 'update tbl_route_into set #ColumnName = 1 where RouteId = #RiD';
SET #DynamicQuery = REPLACE(#DynamicQuery, '#ColumnName', #ColumnName);
EXEC sp_executesql #DynamicQuery, N'#RiD VARCHAR(50)', #RiD = #RiD;
END;
Notes:
You have too many parentheses in your version.
If you are learning to use dynamic SQL, then learn sp_executesql -- and how to use it to pass parameters.
You cannot pass names of things (columns, tables, etc.) as parameters, so that has to be placed directly in the string.
You can pass values into the string, such as #RiD.

Stored procedure with table name as parameter

I have a stored procedure, and I would like to assign the number of rows of that table to a variable and later use that variable.
I am calling the procedure like:
EXEC TEST.dbo.myProc nameOfTable
The procedure is something like:
CREATE PROCEDURE myProc #table_name varchar(1024) AS
BEGIN
DECLARE #Nval INT
/* SOME INSTRUCTIONS */
SELECT #Nval = COUNT(*) FROM #table_name
END
When executing I am getting an error:
Msg 156, Level 15, State 1, Procedure nLQ, Line 57
Incorrect syntax near the keyword 'FROM'.
How would I assign the variable #Nval?
You can't parameterise a table name like that, FROM #table_name. Only way is to execute dynamic TSQL.
Before you do that, read: The Curse and Blessings of Dynamic SQL
try this
ALTER PROCEDURE [dbo].[sp_tablenametest]
#table_name varchar(50),
#PMId int,
#ValueEq int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
SET #cmd = N'SELECT * FROM ' + #table_name +
' WHERE Column1 = ''' + #PMId + '''' +
' AND Column2= ''' + #ValueEq + ''''
EXEC sp_executesql #cmd
END

Stored Procedure to create Insert statements in MySql?

I need a storedprocedure to get the records of a Table and return the value as Insert Statements for the
selected records.
For Instance, The stored procedure should have three Input parameters...
1- Table Name
2- Column Name
3- Column Value
If
1- Table Name = "EMP"
2- Column Name = "EMPID"
3- Column Value = "15"
Then the output should be, select all the values of EMP where EMPID is 15
Once the values are selected for above condition, the stored procedure must
return the script for inserting the selected values.
The purpose of this is to take backup of selected values. when the SP returns
a value {Insert statements}, c# will just write them to a .sql file.
I have no idea about writing this SP, any samples of code is appreicated.
Thanks..
You can do this with mysqldump:
mysqldump --no-create-info --skip-triggers
--where="$COLUMN_NAME='$COLUMN_VALUE'" --databases $DB --tables $TABLE_NAME
To expand on Anuya's answer (which is referenced from http://kedar.nitty-witty.com/blog/mysql-stored-procedure-to-generate-extract-insert-statement) btw...
First need some helper mysql functions:
/*
isNumeric - return 1/true if passed in string is numeric, false otherwise
Usage example: select isNumeric('2012-02-16'); => 0
*/
DROP FUNCTION IF EXISTS `bettermentdb`.`isNumeric`;
DELIMITER ;;
CREATE DEFINER=`betterment-web`#`localhost` FUNCTION `bettermentdb`.`isNumeric`(s varchar(255))
RETURNS TINYINT
DETERMINISTIC
BEGIN
SET #match ='^(([0-9+-.$]{1})|([+-]?[$]?[0-9]*(([.]{1}[0-9]*)|([.]?[0-9]+))))$';
RETURN IF(s regexp #match, 1, 0);
END;;
DELIMITER ;
/*
isNumeric - return an input wrapped in "'" if value is non-numeric, original otherwise.
Depends on isNumeric()
Usage example: select wrapNonNumeric(now()); => '2012-02-16'
select wrapNonNumeric(NULL); => NULL
select wrapNonNumeric(1); => 1
*/
DROP FUNCTION IF EXISTS `bettermentdb`.`wrapNonNumeric`;
DELIMITER ;;
CREATE DEFINER=`betterment-web`#`localhost` FUNCTION `bettermentdb`.`wrapNonNumeric`(s varchar(255))
RETURNS varchar(255)
DETERMINISTIC
BEGIN
RETURN IF(isNumeric(s), s, concat("'", s, "'"));
END;;
DELIMITER ;
Outputs to console with col names defines and non-numeric values wrapped in quotes, while restricting on a given row of input db.table:
DELIMITER ;;
DROP PROCEDURE IF EXISTS GenerateInsertSQL;
CREATE DEFINER=`root`#`localhost` PROCEDURE GenerateInsertSQL(IN in_db varchar(20), IN in_table varchar(32), IN in_row BIGINT)
READS SQL DATA
BEGIN
DECLARE nullableValues varchar(1000);
DECLARE colNames varchar(1000);
DECLARE insertStmnt varchar(2000);
SELECT group_concat(concat('IFNULL(wrapNonNumeric(`',column_name,'`), "NULL")')) INTO #nullableValues from information_schema.columns where table_schema=in_db and table_name=in_table;
SELECT group_concat(concat('`',column_name,'`')) INTO #colNames from information_schema.columns where table_schema=in_db and table_name=in_table;
SET #insertStmnt=concat("select concat('INSERT INTO `", in_db, "`.`", in_table, "`(", #colNames, ") VALUES (', concat_ws(', ',",#nullableValues,"),');') from ", in_db, ".", in_table, " where id = ", in_row, " group by ", #colNames, ";");
PREPARE insertStmnt FROM #insertStmnt;
EXECUTE insertStmnt;
END
DELIMITER ;
DELIMITER $$
DROP PROCEDURE IF EXISTS `sample`.`InsGen` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `InsGen`(
in_db varchar(20),
in_table varchar(20),
in_ColumnName varchar(20),
in_ColumnValue varchar(20)
)
BEGIN
declare Whrs varchar(500);
declare Sels varchar(500);
declare Inserts varchar(200);
declare tablename varchar(20);
declare ColName varchar(20);
set tablename=in_table;
# Comma separated column names - used for Select
select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')'))
INTO #Sels from information_schema.columns where table_schema=in_db and table_name=tablename;
# Comma separated column names - used for Group By
select group_concat('`',column_name,'`')
INTO #Whrs from information_schema.columns where table_schema=in_db and table_name=tablename;
#Main Select Statement for fetching comma separated table values
set #Inserts=concat("select concat('insert IGNORE into ", in_db,".",tablename," values(',concat_ws(',',",#Sels,"),');')
as MyColumn from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",#Whrs, ";");
PREPARE Inserts FROM #Inserts;
EXECUTE Inserts;
END $$
DELIMITER ;
Had to deal with this issue today.
mysqldump is alright but not too friendly to change the WHERE clause.
I end up SQLyog, a MySQL client, it has a feature where you can export a result set of any sql SELECT statement into a bunch of INSERT statements.