TSQL Syntax Error - tsql

I'm wirting a tsql procedure to recreate all the views in one database onto a different dtabase. I'm receiving the error "Incorrect syntax near +" When I look at the code though the syntax appears correct to me. Can anyone tell me what is wrong with this query?
USE [SOURCEDB]
BEGIN
DECLARE #SQL NVARCHAR(MAX)
DECLARE CUR_V CURSOR FOR
SELECT sc.text
FROM sys.views av
JOIN sys.syscomments sc ON sc.id = av.object_id
OPEN CUR_V
FETCH NEXT FROM CUR_V INTO #SQL
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC sp_executesql N'USE [DESTINATIONDB] EXEC sp_executesql ' + #SQL + ''
FETCH NEXT FROM CUR_V INTO #SQL END CLOSE CUR_V DEALLOCATE CUR_V END
Thanks in advance

You can't do the + in the same line as sp_executesql
declare #sql nvarchar(1000)
select #sql = N'USE [DESTINATIONDB] EXEC sp_executesql ' + #SQL + ''
exec sp_executesql #sql
or possibly what you mean is
select #sql = N'USE [DESTINATIONDB] EXEC sp_executesql N''' + #SQL + ''''

Related

How to Get output from nested SP_executeSQL

Can you tell me how to insert executed variable #name in my table?
I had some coding and this is what i managed to do but I do not know whats next:
DECLARE #Name nvarchar(200);
DECLARE #dbcatalog nvarchar(128);
declare #sql nvarchar(4000)
select #name = N' select ID from ' + #DbCatalog + '.dbo.Table2 ';
SET #sql = 'insert into Table2(Name) values (#name)'
exec Sp_executeSQL #sql
Are you trying to copy ID values from one table into another? If so, then:
INSERT INTO Table2 (Name)
EXEC(#Name)

How to select top 10 rows from information.schema.columns list

SELECT TOP 10
*
FROM
(SELECT
COLUMN_NAME, TABLE_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
COLUMN_NAME LIKE '%MAIL%')
I am trying to get the top 10 rows from each of the tables within my search. Any ideas? SQL Server 2008 R2
While nscheaffer's answer is valid, I feel obligated to tell you that you can get the exact same functionality without using a cursor, and also while using a query which might be a bit easier to implement.
Just concatenate all of the possible queries together based off the system tables and then execute them simultaneously, like this:
DECLARE #SQL NVARCHAR(MAX)
;
SELECT #SQL =
(
SELECT 'SELECT TOP 10 * FROM ' + OBJECT_NAME(C.Object_ID) + ';' + CHAR(10)
FROM sys.Columns C
INNER JOIN sys.Tables T
ON C.Object_ID = T.Object_ID
AND T.is_ms_shipped = 0
WHERE C.Name LIKE '%Mail%'
GROUP BY C.Object_ID
ORDER BY C.Object_ID
FOR XML PATH('')
)
;
EXEC sp_ExecuteSQL #SQL
;
If you want to check the SQL before it runs, just comment out the EXEC command and replace it with a SELECT, like this:
SELECT #SQL;
--EXEC sp_ExecuteSQL #SQL
;
I would use a cursor to create dynamic SQL and then execute that SQL. Does this work for you?
DECLARE #SQL NVARCHAR (4000) = ''
DECLARE #Table_Name NVARCHAR(50)
DECLARE TableCursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MAIL%'
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO #Table_Name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = #SQL + '
SELECT TOP 10 * FROM ' + #Table_Name + '
GO
'
FETCH NEXT FROM TableCursor INTO #Table_Name
END
CLOSE TableCursor
DEALLOCATE TableCursor
EXECUTE sp_executeSQL #SQL

Using a Cursor to Create Triggers for all tables in a database

I am using SQL Server 2005
I am trying to create a trigger for each table contained within a database and keep getting an error which I do not understand and can not fix
If anyone has an idea of why I am getting this error or how I can resolve it that would be brilliant.
DECLARE #TableName AS VARCHAR(100)
DECLARE #audit_action as varchar(100)
DECLARE RDS_cusor CURSOR FOR
SELECT TABLE_NAME FROM [RawDataStorage].INFORMATION_SCHEMA.Tables WHERE TABLE_NAME LIKE 't_%' AND TABLE_NAME NOT LIKE 'tbl_%'
OPEN RDS_cursor
FETCH NEXT FROM RDS_cursor INTO #TableName
WHILE ##FETCH_STATUS = 0
BEGIN
CREATE TRIGGER dbo.After_Insert_Trig
ON [dbo].[t_Agent]
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO RawDataStorage_Audit
(TableName,Audit_Action,Audit_Timestamp)
VALUES('TableName','audit_action',getdate());
END
GO
FETCH NEXT FROM RDS_cursor INTO #TableName
END
CLOSE RDS_cursor
DEALLOCATE RDS_cursor
This is the error I am getting:
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'TRIGGER'.
Msg 102, Level 15, State 1, Line 26
Incorrect syntax near 'END'.
Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "#TableName".
any help would be greatly appreachiated
I managed to put this together, its a dynamic query that builds the sql to create the triggers using a cursor to grab the table names from the sysobjects.
CREATE TABLE [dbo].[RawDataStorage_Audit](
ID INT IDENTITY(1,1) NOT NULL,
TableName VARCHAR(50) NULL,
audDateLastChanged DATETIME null
)
Declare #TableName nvarchar(100)
Declare #SQL nvarchar(1000)
declare tables_cursor CURSOR FOR
select [name] from sysobjects
where xtype = 'U'
and [name] not like 'sys%'
order by [name]
Open tables_cursor
fetch next from tables_cursor into #TableName
WHILE ##FETCH_STATUS = 0
Begin
--create trigger for insert on each table
print #SQL
set #SQL = 'create trigger trg_u_'+#TableName+'_Inserted '
set #SQL = #SQL + ' on '+#TableName
set #SQL = #SQL + ' for insert '
set #SQL = #SQL + ' as '
set #SQL = #SQL + ' begin '
set #SQL = #SQL + ' insert into [dbo].[RawDataStorage_Audit] '
set #SQL = #SQL + ' select ''' + #TableName +''', getdate()'
set #SQL = #SQL + ' from inserted'
set #SQL = #SQL + ' end'
exec (#SQL)
print #SQL
fetch next from tables_cursor into #TableName
end
CLOSE tables_cursor
DEALLOCATE tables_cursor

SQL Server Exception handling in a cursor defined query

Here is the script I am using to run against all the databases on sql server but somehow the script stops when the database is in transition so all I want to do is the script needs to skip the database that is in transition and proceed with rest of the databases. Any help would be appreciated.
declare #name varchar(max)
SET #starttime = GETDATE()
Declare DB_cursor cursor for
SELECT Name
FROM sys.databases
WHERE name NOT IN ('master', 'model', 'msdb', 'tempdb')
AND is_read_only = 0
AND is_in_standby = 0
AND state = 0
OPEN DB_cursor
FETCH NEXT FROM DB_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC(' use [' + #name + '] IF EXISTS (select name from sys.objects where name=''#Tablename'') UPDATE STATISTICS [' + #SchemaName + '].[' + #TableName +'](['+#StatsName+']) WITH FULLSCAN ')
FETCH NEXT FROM DB_cursor INTO #name
END
CLOSE DB_cursor
DEALLOCATE DB_cursor
Try:
DECLARE #sql NVARCHAR(MAX)
SET #sql = ' use [' + #name + '] IF EXISTS (select name from sys.objects where name=''#Tablename'') UPDATE STATISTICS [' + #SchemaName + '].[' + #TableName +'](['+#StatsName+']) WITH FULLSCAN ' )
EXEC sp_executesql #sql = #sql

Adding GUID parameter to a sql string

I am having complications adding a guid type to a sql string and getting the query to go. I have to write the sql this because I need to pass the name database as a parameter.
The following code is what I'm trying to do but it doesnt work. No matter what I do it doesn't read the GUID correctly. It gives me the following error when executing the stored proc. Probably because guid has "-" in them
Incorrect syntax near '-'.
Here's the code:
ALTER PROCEDURE [dbo].[templatesAndBaskets_Select]
#guid uniqueidentifier,
#DatabaseName varchar(50)
AS
BEGIN
Declare #sql varchar(max)
Set #sql=
'select soldtoid
from ' + #DatabaseName + '.templatesAndBaskets' +
' where ordergroupid = ' + CONVERT(varchar(max),#guid)
print #sql
EXECUTE SP_EXECUTESQL #sql
END
You probably just simply need to put single quotes around the GUID :
SET #sql =
N'SELECT soldtoid FROM ' + #DatabaseName + N'.templatesAndBaskets' +
N' WHERE ordergroupid = ''' + CONVERT(nvarchar(max), #guid) + N''''
That should result in a SQL statement something like this:
SELECT soldtoid FROM database.templatesAndBaskets
WHERE ordergroupid = '5E736CE7-5527-40ED-8499-2CA93FC7BC9C'
which is valid - yours without the single quotes around the GUID isn't valid...
Update: you also need to change your #sql variable to NVARCHAR for sp_Executesql - try this:
ALTER PROCEDURE [dbo].[templatesAndBaskets_Select]
#guid uniqueidentifier,
#DatabaseName NVARCHAR(50)
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
SET #sql =
N'SELECT soldtoid FROM ' + #DatabaseName + N'.templatesAndBaskets' +
N' WHERE ordergroupid = ''' + CONVERT(nvarchar(max), #guid) + N''''
PRINT #sql
EXECUTE sp_ExecuteSQL #sql
END
Does that work??
Put the #guid between '
ALTER PROCEDURE [dbo].[templatesAndBaskets_Select]
#guid uniqueidentifier,
#DatabaseName varchar(50)
AS
BEGIN
Declare #sql varchar(max)
Set #sql=
"select soldtoid from " + #DatabaseName + ".templatesAndBaskets" +
" where ordergroupid = '" + CONVERT(varchar(max),#guid)+"'"
print #sql
EXECUTE SP_EXECUTESQL #sql
END