SQL server-declare local variable: "there is already an object named '' in the database" - sql

I wrote the following stored procedure, in which I use a local variable 'syncParam':
declare #syncParam bit
select isSync into syncParam from MyTable where id=#id
if (#syncParam='True')...
else ...
return #syncParam
When I executed this stored procedure at the first time it worked, but after that I get the following error: "there is already an object named 'syncParam' in the database".
What did I miss?
Thanks in advance.

You want
select #syncParam = isSync from MyTable where id=#id
SELECT INTO will insert records into a new table. Go look, you should have a syncParam table now.

you might consider using a temp table .. just rename the table #syncParam

Related

Deleting the Global Temp table and then creating the Global temp table with same name is giving ambiguity error

Below is the SQL statement for Deleting the global temp table and creating it again.
if object_ID('tempdb..##TempTable123') is not null
begin drop table tempdb..##TempTable123 end
GO
Select * into ##TempTable123 from ##TempTable1
After executing the Select statement, I am getting the following Error
"The reference to temp table name '##TempTable123' is ambiguous and cannot be resolved. Use either '##TempTable123' or '##TempTable123'."
Try to add tempdb.. to the select:
Select * into tempdb..##TempTable123 from tempdb..##TempTable1

Getting Error with ##TempTable

I want to use ##TempTable to get value from oracle db in my sql Server query, but always get error, the error says
##TempTable is Invalid object name '##TempTable '.
here's the code where I use ##TempTable
SET #sQuery = 'SELECT * INTO ##TempTable
FROM OPENQUERY(ITCP,''SELECT * FROM DB.WINFO WHERE SCH_DATE = '''''+
CONVERT(VARCHAR(10),#DDATE,121) +''''''' ) A' EXEC(#sQuery)
I confused, Should I Declare Query to create the ##TempTable like create Table like usual or by that query the temp table should automatically created? because I always getting error
I think the issue is your temp table is being created in one scope, and your dynamic query is being executed in another.
A few things to try:
Create the ##temptable first, then populate it in your dynamic query.
Try prefixing the table name with tempdb.. (so tempdb..##temptable).
Use a persistent table (not a temp table).
Hope this helps.

Create Database and Table Conditionally

I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:
IF (db_id('db') is null) BEGIN
print 'Must create the database!';
CREATE DATABASE db;
END
USE db;
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
I'm getting a strange error with this:
Database 'db' does not exist. Make sure that the name is entered correctly.
I'm guessing that it's parsing the script before running it and finding that 'db' doesn't exist, so it can't use it.
There must be a solution to this. Any help is appreciated.
SOLVED!
I realised 5 minutes after posting that the GO keyword solves the problem. Here is the fixed code:
IF (db_id('db') is null) BEGIN
print 'Must create the database!'
CREATE DATABASE db;
END
GO
USE db
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
Sorry for wasting everyone's time.
SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.
If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT for SQL Server and MySQL, respectively.
Something along the lines of Check if table exists in SQL Server would probably work (With a slight change)
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
I might suggest using the built-in SQL syntax -
CREATE DATABASE name IF NOT EXISTS;
And subsequently
CREATE TABLE name(definition) IF NOT EXISTS;

SQL Server Import and Export wizard gives invalid object error on stored procedure with temp table

I created a stored proc that creates a temp table, inserts, selects then drops. Executing the stored proc within SQL Server Management Studio works fine and gives the expected result.
CREATE PROCEDURE usp_TempTableTest
-- Add the parameters for the stored procedure here
#color VARCHAR(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
CREATE TABLE #tmptable (
color VARCHAR(10)
)
INSERT INTO #tmptable (color) VALUES (#color)
SELECT color FROM #tmptable
DROP TABLE #tmptable
END
GO
However, when creating in the Import/Export tool and using that stored proc as the data source, it gives me the error:
Invalid object name '#tmptable'.
Any idea why this would happen? If I change it to a table variable it seems work fine with Import/Export, but I don't understand why it is not working with a temp table.
When I run a mimicked stored procedure, like yours above, in SSMS, I can get the data returned like you mentioned in the procedure. However, if I try the #tmptable, like you did, I also get the same error because the DROP TABLE removes it. From what I can tell, the import/export is basically a final INSERT process. The reason it works with the table variable is because the data still exist on the final insert; in the case of the DROP TABLE, it does not. For instance, when I remove the DROP TABLE, it works.
I might be wrong here, but it seems the logic when it's an import or export in the case of the above procedure is
INSERT data
SELECT data
DROP data
INSERT (import/export): this generates the "Invalid object name tmptable'"
With the variable (or no DROP), it's
INSERT data
SELECT data
INSERT (import/export)
In the second case, the data still exist. In the first case, they're gone. One way around it if you want to use the #tmptable, start your code with:
IF OBJECT_ID('tempdb..#tmptable') IS NOT NULL DROP TABLE #tmptable
Put "SET FMTONLY OFF;" right above "SET NOCOUNT ON"
http://msdn.microsoft.com/en-us/library/ms173839.aspx

SQL Server Delete on read

Is there an easy way in SQLServer touse data as READ_ONCE? What I mean is, can I set it to delete a row after it has selected it?
Off the top of my head, the only way I can think of would be to restrict all logins to prohiibit any Select access, and only allow access through a stored procedure "FetchMyWhateverData" and then delete the rows as second SQL statement inside the stored proc.
CreateProcedure FetchMyWhateverData
#MyEntityId Integer,
As
Set NoCount On
Select * From TableName
Where Id = #MyEntityId
Delete TableName
Where Id = #MyEntityId
Return 0
-- and adding in the other appropriate infrastructure code of course.
If you read it with DELETE ... OUTPUT .... This is how queues work.
You could do this easily if the data is accessed through a stored procedure. You can select the data into a temp table, delete the data and return the temp. All wrapped in a transaction of course.