Rename table in SQL Server - sql

I want to rename a table. But I get an error when running the code. What is the correct code?
DECLARE #TABLE_NAME VARCHAR(100)
SET #TABLE_NAME = 'Employee_Destination'
IF EXISTS (SELECT NAME FROM SYS.tables WHERE NAME = #TABLE_NAME)
BEGIN
EXEC sp_rename #TABLE_NAME, #TABLE_NAME += '_2'
END
This error message (SSMS):
Incorrect syntax near #TABLE_NAME
This error message (SSIS Project) :
[Execute SQL Task] Error: Executing the query "DECLARE #TABLE_NAME
VARCHAR(100) DECLARE #TABLE_TE..." failed with the following error:
"An error occurred while extracting the result into a variable of type
(DBTYPE_I4)". Possible failure reasons: Problems with the query,
"ResultSet" property not set correctly, parameters not set correctly,
or connection not established correctly.
Note: I run this code in a SSIS project
Thank you.

Related

Error during sp_refreshsqlmodule after altering table type

I am trying to add a column to a user-defined table type.
I have done some research and here is what I have now:
-- First, rename existing table type to something else
EXEC sp_rename 'TT_MY_TABLE_TYPE', 'TT_MY_TABLE_TYPE_1'
-- Create the new table type
CREATE TYPE [dbo].[TT_MY_TABLE_TYPE] AS TABLE(
[MY_FIELD] [varchar](20) NULL
)
GO
-- Do a refresh of the SP/views so that the SP/views will refer to the new table type
-- Save the list of dependencies to a temporary table
SELECT 'sp_refreshsqlmodule ' + quotename('MySchemaName.' +object_name(referencing_id), '''') AS SQL_CMD
INTO #TEMPSQL
FROM sys.sql_expression_dependencies
WHERE referenced_class_desc = 'TYPE' and referenced_entity_name = 'TT_MY_TABLE_TYPE';
DECLARE #sql NVARCHAR(1000)
-- Do a loop for the list of dependencies, use dynamic SQL to execute the SQL commands
DECLARE c_Cur CURSOR FOR
SELECT SQL_CMD
FROM #TEMPSQL
OPEN c_Cur
FETCH NEXT FROM c_Cur INTO #sql
WHILE (##FETCH_STATUS = 0)
BEGIN
EXEC SP_EXECUTESQL #statement = #sql
FETCH NEXT FROM c_Cur INTO #sql
END
CLOSE c_Cur
DEALLOCATE c_Cur
-- Drop the old table type
DROP TYPE TT_MY_TABLE_TYPE_1
DROP TABLE #TEMPSQL
Unfortunately, while refreshing stored/procedures (their dependencies) to reflect the new type I am getting the following error:
Procedure sp_refreshsqlmodule_internal, Line 85 [Batch Start Line 0]
Operand type clash: TT_MY_TABLE_TYPE is incompatible with
TT_MY_TABLE_TYPE_1.
I expect that the error is something else since all I did was adding one column to the new type.
When I try to alter the function that has this type as a dependency, I have the same Operand type clash error
Could you help me identify, what is the root cause of this problem?
To anyone, that may come across this problem:
The issue was nested dependencies.
You need to run sp_refreshsqlmodule starting from the bottom of the dependency hierarchy. If you try to refresh the Stored Procedure, that uses this table type and passes it further, you will get this operand type clash error

How to use Declared variables in JSON root, while convert table data to JSON in SQL server?

I am using SQL server.
I try to get JSON value from table data in SQL server. In my case I want to get ROOT as what I get from the Declared VARIABLE.
Here is my code:
DECLARE #TpiType VARCHAR(64)='SMS'
,#TpiName VARCHAR(24)='PLIVO'
,#Purpose VARCHAR(24)='SYSTEM'
DECLARE #Purpose2 VARCHAR(24)
SET #Purpose2=#Purpose +'%'
SELECT Name,Value
FROM MyTable
WHERE Type=#TpiType AND Name=#TpiName
AND NAME LIKE #Purpose2
FOR JSON AUTO,ROOT(#TpiType)
When I try this it shows me the error:
Incorrect syntax near '#TpiType'.
But If I give the string value directly to the root, it works fine. But when I pass the variable, it throws error.
Please help me to fix this issue. Thanks in advance.
You might find using dynamic sql helpful here:
DECLARE #TpiType VARCHAR(64)='''SMS'''
,#TpiName VARCHAR(24)='''PLIVO'''
,#Purpose VARCHAR(24)='''SYSTEM'
DECLARE #Purpose2 VARCHAR(24)
SET #Purpose2=#Purpose +'%'''
Declare #sql VARCHAR(2000)
Set #sql = 'SELECT Name,Value
FROM MyTable
WHERE Type=' +#TpiType+' AND
Name=' +#TpiName +'
AND NAME LIKE ' +#Purpose2+'
FOR JSON AUTO,ROOT(' +#TpiType+')'
Print #sql -- check if this prints the sql script correctly
--Exec (#sql) -- run this to execute dynamically created script

SQL error - Incorrect syntax near the keyword 'Database'

I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:
DECLARE #DBName NVARCHAR(MAX);
SET #DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + #DBName);
But I got the error message:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.
Do know what is wrong there?
I'm not sure about the keyword database in the error message, but I do spot problems:
You concatenate USE and the databasename without a space: USENAV01 doesn't work. You should use 'USE ' + QUOTENAME(#DBName).
Secondly, I don't know what the intention is, but if you do EXECUTE ('USE ' + #DBName); followed by other (dynamic) queries, the following queries are executed on your current connection. In other words, the USE XXX doesn't matter for the following queries.
Thirdly, as mentioned by Jesse in below comment; if you have more than one database with a name like '%NAV%' (which your question suggests), your code is only executed for one of those databases. Which one that will be is unpredictable without an order by. If you want to execute code for all relevant databases, you have to loop through them.
Put a space after USE and put brackets around the database name:
DECLARE #DBName NVARCHAR(MAX);
SET #DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + #DBName + ']');

Cannot find 'server\db' in sys.servers

My SQL Server job is supposed to create a linked server and query it. However there seems to be an issue with the name and I can not figure out where. I tried googling and it seems that linked server is made, but the query "misreads" the name. Please tell why this happens or where am I messing up.
DECLARE #tmp_key VARCHAR(14)
DECLARE #db cursor
DECLARE #sql NVARCHAR(MAX)
exec sys.sp_addlinkedserver '[server\db]'
SET #db = CURSOR FOR
Here is the error part:
SELECT RIGHT('000'+CAST([CONro]AS VARCHAR(4)),4)
FROM [server\db].[TKYHT].[dbo].COMPANY
WHERE [CONro] NOT IN ('1','95','104','105','183','213','275','603','620','802','998','1001','1002',
'1105','1112','1113','1122','1179','1183','1189','1458','1508','1516','1575','1599','1602',
'1691','1841','2184','3073','3074','3980','3989','6158','6164','9990','9999')
ORDER BY [CONro] ASC
The error is;
Cannot find 'server\db' in sys.servers , Verify that the correct
server name was specified. If necessary, execute the stored procedure
sp_addlinkedserver to add the server to sys.servers. [SQLSTATE 42000]
(Error 7202). The step failed.
Some ok code here:
exec sys.sp_dropserver '[server\db]'

BCP on global ##temp table error

I'm using the following query to write the data in a external file:
declare #sql varchar(8000);
select #sql = 'bcp tempdb.##hmscript out
F:\HMS\test.txt -c -t, -T -S GIT2B-01\MON'
select #sql
exec master..xp_cmdshell #sql;
When testing the bcp in cmd window I'm getting the following error:
SQLState = 37000, NativeError = 11525
Error = [Microsoft][SQL Server Native Client 11.0][SQL Server]The metadata could
not be determined because statement 'select * from ##hmscript' uses a temp table.
Somebody has a solution for this?
Thanks in advance,
David
If the table doesn't exist, you'll get this error.
Create the table and try again, and you should get what you want.