T-Sql what's wrong with this - sql-server

I'm actually an ORACLE-guy. But I now I have to create a simple function in T-SQL (customer uses SQL-Srv 2008, no chance upgrading)
error message:
Msg 156, Level 15, State 1, Procedure create_view, Line 9
Incorrect syntax near the keyword 'view'.
so? what's wrong with this create view stmt?
create function create_view (#tab_name varchar(64))
returns int
as
begin
declare
#error int
;
begin
create view [dbo].[target_list]
as select * from #tab_name
;
set #error=##ERROR
return #error
end
end
thx in advance

In SQL Server, function is allow only SELECT statement. Function does not support DML and DDL statements. Reference
DML Statments includes INSERT,UPDATE,DELETE
DDL Statement includes CREATE,DROP

Related

SQL, cursor for one time initialization, Must declare scalar variable

I am using a cursor to one time populate a table with all tenants that are in the tenants table. I want to make sure that the tenantId will be set with a name of General in my navigations table. But for some reason it thinks that my variable isn't set.
I tried the following code
**** Script for SelectTopNRows command from SSMS ******/
declare #tenantId int
declare #tenantName nvarchar(100)
DECLARE tenantCursor CURSOR FOR
SELECT Id, [Name]
FROM [dbo].[Tenant]
OPEN tenantCursor;
FETCH NEXT FROM tenantCursor INTO #tenantId, #tenantName;
WHILE ##FETCH_STATUS = 0
BEGIN
print #tenantId
print #tenantName
SET #tenantId = #tenantId
Insert INTO [dbo].Navigations ([Name, TenantId])
VALUES ('Algemeen', #tenantId);
GO
FETCH NEXT FROM tenantCursor INTO #tenantId, #tenantName;
END;
CLOSE tenantCursor;
DEALLOCATE tenantCursor;
GO
I got the follwoing error:
Msg 102, Level 15, State 1, Line 22
Incorrect syntax near ';'.
Msg 137, Level 15, State 2, Line 26
Must declare the scalar variable "#tenantId".
The structure of my tables
Any help will be much appreciated.
Rodney
The simple solution is to just use SQL in the set based manner with which it is designed and run the following instead of your cursor:
insert into dbo.Navigations ([Name]
,TenantId
)
select 'Algemeen'
,Id
from dbo.Tenant;
Outside of the above however, you shouldn't have a go in the middle of your cursor and you have missed some square brackets on your insert:
Insert INTO [dbo].Navigations ([Name, TenantId])
should be
Insert INTO [dbo].Navigations ([Name], [TenantId])

Incorrect syntax near the keyword “AS” when alter trigger

i created trigger called trgInsteadofdeleteEmp
and i just want to alter it, i wrote the following SQL code
alter trigger trgInsteadofdeleteEmp on Emp
instead of delete
as
begin
declare #id int , #name nvarchar(100)
select #id =id from deleted
select #name = name from deleted
insert into EmployeeAudit values (#id ,#name + 'tried to delete at' + GETDATE() as varchar(50))
end
and have the following output:
Msg 156, Level 15, State 1, Procedure trgInsteadofdeleteEmp, Line 8 Incorrect syntax near the keyword 'as'.
can someone point me in the direction of how to find the error
Thanks.
No, no, no, no, no.
Don't make the mistake of assuming that inserted and deleted have only one row. You are just putting errors in your code that are going to pop up at an unexpected time. I actually wish that SQL Server flagged this usage when creating the trigger.
Instead:
alter trigger trgInsteadofdeleteEmp on Emp
instead of delete
as
begin
insert into EmployeeAudit(id, name)
select id,
name + ' tried to delete at ' + convert(varchar(255), GETDATE(), 121) )
from deleted d;
end;
Your error is caused by the as. There seems to be a missing cast() function. But that is not the right fix. With date/times, use convert() or format() along with the desired format.
Other suggestions:
Always include the column names when doing an insert. In fact, an audit table really should have an identity id column, createdBy, and createdAt columns, all with default values.
Look at the strings that will be produced and be sure they are readable.
Use semicolons to end statements.
Don't rely on default formatting for date/time values.

Return Stored Proc Results in CTE

Is it possible for me to call a stored proc into a CTE. I have a login to our reporting DB that is only RO. I have write access to our UAT but would like to query live data.
So can I use a stored proc in a CTE?
with clientOwes as (
exec des_Batch_GetApplicationClientOwesList
)
select a.des_applicationnumber
from des_heapplicationset a
where a.des_heapplicationid in (select applicationid from clientowes)
result was: Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'exec'.
Answer adapted from dialogue in comments:
You can use a stored procedure to populate a table variable, which Read Only access does allow you to create. You won't need to use OpenRowSet to populate it either. Just do:
INSERT INTO #MyTableVariable
EXEC MyStoredProcedure
I do this in a lot of places myself where I need to treat Stored Proc results as a table that I can JOIN or UNION with other tables.

sql script needs if statement wrapped

i'm trying to wrap a simple function within an a check for existence why am i getting incorrect syntax?
updated:
GO
IF EXISTS (SELECT TOP 1 * FROM Customers)
BEGIN
USE [rstestDB]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [dbo].[udf_GetName]
(
#p1 nvarchar(25)
)
RETURNS varchar
AS
BEGIN
DECLARE #Result varchar(25)
SELECT #Result = 'John Doe'
RETURN #Result
END
END
GO
Getting following error:
Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'FUNCTION'.
Msg 178, Level 15, State 1, Line 19
A RETURN statement with a return value cannot be used in this context.
GO is a batch separator.
GO is a command recognized by the sqlcmd and osql utilities that send commands to the SQL engine, it's not valid SQL.
Take out all the GOs except for at the very end.
A simpler example that will also fail:
IF 1=1
BEGIN
SELECT 'FOO'
GO
END
All your settings should really be at the very beginning of the script since they will persist for the length of the session.

Error with the below script

I am performing the below operation. I am getting the error and unable to find what the error is.Could any one help me finding it.
a) Check for the availability of DESTINATION data base. If it is not exist, create the data base and move the tables to the data base.
b) If the table exists in the DESTINATION data base then no process required for the table.
if db_id('Destination')is null
begin
Create database Destination
select * into TabDestination from [Source].[dbo].[TabSource]
end
else
begin
use Destination
go
if('TabDestination' in (select name from sys.objects where type = 'u'))
insert into TabDestination select * from [Source].[dbo].[TabSource]
end
I am getting fallowing error
Msg 911, Level 16, State 1, Line 8
Database 'Destination' does not exist. Make sure that the name is entered correctly.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'end'.
Your problem is with the USE, from the documentation:
USE is executed at both compile and execution time...
If the database specified doesn't exist at compile time then the query will fail. You can see this by trying to run the following query:
IF 1 = 2
BEGIN
USE NonexistantDatabase
END
This query fails despite the fact that the USE statement is never executed.
You should instead change your query to use database qualified names, for example:
INSERT INTO Destination.dbo.Table SELECT * FROM Source.dbo.Table
Few problems here:
After Create database Destination you need to use that database before you do the select * into TabDestination... as you will create TabDestination in some other DB.
The Go in the middle of the begin...end block won't work.
To specify your database for the inserts to TabDesitination you'd be better to use the fully qualified name of the table than calling Use, eg Insert Destiation.dbo.TabDestination...
You need to use If Exists (select... for the second if statement.
Because your Database may not exists when the script compiles, a lot of the sql needs to be exec'd dynamically.
So your script could be re-written as:
if db_id('Destination')is null
begin
Create database Destination
exec ('select * into Destination.dbo.TabDestination from [Source].[dbo].[TabSource]')
end
else
begin
if exists (select name from Destination.sys.objects where name = 'TabDestination' and type = 'u')
insert into Destination.dbo.TabDestination select * from [Source].[dbo].[TabSource]
end
A variation on #Jon Egerton's answer, however there is one case you've neglected to cover: the database exists but the table does not.
DECLARE #sql NVARCHAR(MAX) = N'SELECT *
INTO Destination.dbo.TabDestination
FROM Source.dbo.TabSource;';
IF DB_ID('Destination') IS NULL
BEGIN
PRINT 'Creating database...';
CREATE DATABASE Destination;
PRINT 'Selecting into new table...';
EXEC sp_executeSQL #sql;
END
ELSE
BEGIN
IF EXISTS (SELECT 1 FROM Destination.sys.tables WHERE schema_id = 1
AND name = N'TabDestination')
BEGIN
PRINT 'Inserting into existing table...';
INSERT Destination.dbo.TabDestination SELECT * FROM Source.dbo.TabSource;
END
ELSE
BEGIN
PRINT 'Selecting into new table...';
EXEC sp_executeSQL #sql;
END
END
EDIT
Added PRINT statements for debugging purposes, as I suggested in the follow-up to #Jon's answer.
You just need to get rid of the GO command, its a batch separator so it breaks your begin/end. Oh and you can't use USE like that either.

Resources