Using variable for column name in SQL Server stored procedure - sql-server-2008

I am using SQL Server 2008 and still cannot figure out what's wrong in the stored procedure below:
SET #DataDD = 'DataPM'+#DD
SET #SQL = 'UPDATE TraineeMonthlyAttendRecord'+
' SET '+#DataDD+ '="9" '+
'WHERE TraineeID='+#TraineeID+' and RecordID ='+#RecordID
EXEC(#SQL)
Thanks!

Related

I there any way to display the current date as column header in MySql?

Wherever I try running SELECT CURDATE(); It's running fine but
on running SELECT CURDATE() AS CURDATE(); it's throwing
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'curdate()' at line 1.
The format I want is
||2020-05-15||
||2020-05-15||
I am a newbie in MySql is there any way to get the column header as the Current date.
// In SQL Server Reference:
DECLARE #ColumnName AS VARCHAR(20)
DECLARE #SQL AS VARCHAR(200)
SET #ColumnName = CONVERT(VARCHAR,GETDATE(),106)
SET #SQL = 'SELECT CONVERT(VARCHAR,GETDATE(),106) AS ' + CHAR(39) + #ColumnName + CHAR(39)
EXEC(#SQL)

Creating a MySQL stored procedure to update records

I'm converting all of my existing MSSQL databases and stored procedures am stuck on a new stored procedure where I need to update an existing record. The procedure gets called from a web form once a record has been inserted into the database and en email sent successfully (or at least passed off to the SMTP server)
I've had a working procedure in MSSQL for a long time but am trying to convert it to MySQL. I'm passing in 3 variables - a bit indicating the email got sent, a string indicating which SMTP server has been used to sent the email and a unique record id so I'll know what record to update. I'm also adding the date and time to another field to know when the procedure ran.
I've got the following but keep getting an error "#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 7 - yet I don't see anything off at line 7 - at least to my eye.
The code I'm trying to use is:
CREATE PROCEDURE `sp_Test`(
`emailSent_In` BIGINT UNSIGNED,
`emailTransport_In` VARCHAR(100),
`formSecret_In` VARCHAR(32)
)
BEGIN
SET #`query` := CONCAT('UPDATE ',`tbl_JustSayThanks`,'
SET `emailSent` = `emailSent_In`,
`emailTransport` = ',`emailTransport_In`,',
`emailSentDate` = NOW()
WHERE `formSecret` = ', `formSecret_In`, '');
PREPARE `stmt` FROM #`query`;
EXECUTE `stmt`;
#`query` := NULL;
DEALLOCATE PREPARE `stmt`;
END//
DELIMITER ;
Just FYI, I'm using the CONCAT based on a previous answer I received from wchiquito and will be passing in the table name eventually. But, I wanted to get it to work on a simplified level before going there.
The following is wrong:
SET #`query` := CONCAT('UPDATE ',`tbl_JustSayThanks`,'
because you seem to be concatenating your SQL text with the value of tbl_JustSayThanks, but I think you mean to use the identifier itself. This should therefore be:
SET #`query` := CONCAT('UPDATE `tbl_JustSayThanks`',
The following is wrong:
`emailTransport` = ',`emailTransport_In`,',
because the variable is a VARCHAR but you don't quote it as a string literal in your SQL statement. It's easy to get mixed up with the multiple levels of quoting. It should be:
`emailTransport` = ''', `emailTransport_In`, ''',
The following is wrong for the same reason:
WHERE `formSecret` = ', `formSecret_In`, '');
it should be:
WHERE `formSecret` = ''', `formSecret_In`, '''');
This still suffers from SQL injection problems, unless you can guarantee that the input parameters are safe (which is not a good assumption). If you need to concatenate values into your SQL expressions, you should use the QUOTE() function to do escaping:
SET #query = CONCAT('
UPDATE tbl_JustSayThanks
SET emailSent = ', QUOTE(emailSent_In), '
emailTransport = ', QUOTE(emailTransport_In), '
emailSentDate = NOW()
WHERE formSecret = ', QUOTE(formSecret_In));
More comments:
You don't need to delimit every identifier with back-ticks, only those that conflict with SQL reserved words, or contain whitespace or punctuation or international characters. None of your identifiers you show require delimiting.
When you use prepared statements, you should use query parameters with the ? placeholders, intead of concatenating variables into the SQL string. You don't quote parameter placeholders in your SQL query. That way you won't run into hard-to-debug syntax errors like the ones you found.
Here's an example showing the fixes:
CREATE PROCEDURE sp_Test(
emailSent_In BIGINT UNSIGNED,
emailTransport_In VARCHAR(100),
formSecret_In VARCHAR(32)
)
BEGIN
SET #query = '
UPDATE tbl_JustSayThanks
SET emailSent = ?,
emailTransport = ?,
emailSentDate = NOW()
WHERE formSecret = ?';
SET #es = emailSent_In;
SET #et = emailTransport_In;
SET #fs = formSecret_In;
PREPARE stmt FROM #query;
EXECUTE stmt USING #es, #et, #fs;
DEALLOCATE PREPARE stmt;
END//
DELIMITER ;
Final comment:
Your example query has no dynamic syntax elements, only dynamic values. So you don't need to use a prepared statement at all.
This is how I'd really write the procedure:
CREATE PROCEDURE sp_Test(
emailSent_In BIGINT UNSIGNED,
emailTransport_In VARCHAR(100),
formSecret_In VARCHAR(32)
)
BEGIN
UPDATE tbl_JustSayThanks
SET emailSent = emailSent_In,
emailTransport = emailTransport_In,
emailSentDate = NOW()
WHERE formSecret = formSecret_In;
END//
DELIMITER ;
You should also be aware that MySQL stored procedures are greatly inferior to Microsoft SQL Server. MySQL doesn't keep compiled stored procedures, it doesn't support packages, it doesn't have a debugger... I recommend you do not use MySQL stored procedures. Use application code instead.

Sqlserver: Variable database name in create database query is throwing error

Use master
GO
Declare #dbName As VARCHAR(50)
SET #dbName = 'TestDB'
CREATE DATABASE #dbName
Above sqlserver is script is giving me error. Why?
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '#dbName'.
You can not use dynamic sql and ddl as mixed.
Use dynamic sql .
Try this code:
Use master
GO
Declare #dbName As VARCHAR(50)
DECLARE #Q VARCHAR(MAX)
SET #dbName = 'TestDB'
SET #Q='CREATE DATABASE '+ #dbName
EXEC(#Q)
If won't work because you're passing a VARCHAR type and for the creation of a database, it takes an object instead of a Varchar. Else, you'll need to pass the whole query as a string to execution;
Declare #dbName As VARCHAR(50) = 'TestDB'
DECLARE #Creation VARCHAR(50) ='CREATE DATABASE '+ #dbName
EXEC(#Creation)

Entity Framework no columns from simple query

I have the following stored procedure:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetData]
#taskName VARCHAR(205) = NULL
AS
BEGIN
SELECT *
FROM [dbo].[Table] WITH (NOLOCK)
WHERE #taskName IS NULL
OR #taskName = ''
OR Name LIKE '%' + #taskName + '%'
ORDER BY Name
END
Now I created an File.edmx generated model, selected the GetData stored procedure, when I do a function import and I get "Get Column Information", it says
The selected stored procedure returns no columns
I am dbo_owner on the database and it is my user that is in the app.config on generation, and I am even storing the password in app.config (temporarily), when I run the procedure from Management Studio, it shows the columns..
I'm puzzled!
You need to specify the field names in your select statement rather than just using the *
try
ALTER PROCEDURE [dbo].[GetData]
#taskName VARCHAR(205) = NULL
AS
BEGIN
exec ('SELECT * FROM [dbo].[Table] WITH (NOLOCK) WHERE ' + #taskName + 'IS NULL OR ' + #taskName + ' = \'\' OR Name LIKE \'%' + #taskName + '%\' ORDER BY Name')
END
GO
I would try the same process but using only
SELECT *
FROM [dbo].[Table] WITH (NOLOCK)
instead of the full query. Then you can alter your proc to add the where.
Sometimes EF has problems identifying the return columns due to the were clause

What is best method to read a column value having quote ' and insert into a different table?

Hey I have a name column in my table, suppose i get have name O'Neil, when ever i read this name and insert into a linked server throught dynamic SQL I get error...How to handle this...
One method is to check if my name has a quote(') but I am researching if someone coul
my dynamic SQL looks like
'name = '+#quote+#name+#quote
#quote is nothing but below...
set #quote = ''''
thanks,
Naga
I guess you problem could be demonstrated with this code:
declare #Name varchar(20)
set #Name = 'O''Neil'
declare #SQL nvarchar(100)
set #SQL = 'select '+#Name
exec (#SQL)
Result: Unclosed quotation mark after the character string 'Neil'.
You can use quotename to properly add quote characters:
set #SQL = 'select '+quotename(#Name, '''')
The better alternative is to use sp_executesql and pass #Name as a parameter.
set #SQL = 'select #Name'
exec sp_executesql #SQL, N'#Name varchar(20)', #Name
If you can use PreparedStatements then this is better way of inserting/updating many rows. Such code in Jython (using Javas JDBC) looks like:
db = DriverManager.getConnection(jdbc_url, usr, passwd)
pstm = db.prepareStatement("insert into test (lastname) values (?)")
pstm.setString(1, "O'Neil")
reccnt = pstm.execute()
You will find similar PreparedStatement in ODBC, .net etc. It should be much lighter for database for massive inserts then creating full SQL insert statement for every inserted value.
Such massive insert from CSV file can look like:
pstm = db.prepareStatement("insert into test (lastname) values (?)")
while not csvfile.eof():
lastname = csvfile.next_line()[0]
pstm.setString(1, lastname)
reccnt = pstm.execute()