Stored Procedure in T-SQL [closed] - sql-server

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I am trying to create a stored procedure for creating login into SQL Server. The stored procedure is complied successfully but I am getting error when I am executing the stored procedure.
CREATE OR ALTER PROCEDURE dbo.sp_login_1
(#userId varchar(15),
#passwd varchar(15),
#db varchar(15))
AS
BEGIN
DECLARE #stmt NVARCHAR(1000)
SET #stmt = 'CREATE LOGIN ' + #userId +
' WITH PASSWORD = ' + #passwd + ', ' +
' DEFAULT_DATABASE = ' + #db + '; ' +
'CREATE USER' + #userId +
' FROM LOGIN ' + #userId + ';' +
'ALTER ROLE groupAdmin ADD MEMBER' + #userId + ';'
EXEC sp_executesql #stmt;
END;
exec dbo.sp_login_1 #userId='user1', #passwd ='pwd', #db ='dbo.myDB';
The following error is displayed.
Msg 102, Level 15, State 1, Line 159
Incorrect syntax near 'pwd'.
Msg 102, Level 15, State 1, Line 159
Incorrect syntax near ';'.

You must add single quotes for the password field. Best to do this with QUOTENAME
SET #stmt = 'CREATE LOGIN ' + QUOTENAME(#userId) +
' WITH PASSWORD = ' + QUOTENAME(#passwd, '''') + ', ' +
' DEFAULT_DATABASE = ' + QUOTENAME(#db) + '; ' +
'CREATE USER' + QUOTENAME(#userId) +
' FROM LOGIN ' + QUOTENAME(#userId) + ';' +
'ALTER ROLE groupAdmin ADD MEMBER ' + QUOTENAME(#userId) + ';'
The reason the error message refers to pwd (which is not in the script) is because it clearly passed the pwd as a #passwd parameter.

Related

What's wrong with string?

I tried to compose a string to execute in SQL Server:
DECLARE #sql varchar(4000) =
'EXEC sys.sp_addextendedproperty #name=N''MS_Description'', #value=N''' + 'описание' + ''', #level0type=N''SCHEMA'',#level0name=N''' + 'rudata_r2' + ''', #level1type=N''TABLE'',#level1name=N''' + 'Subscriptions' + ''', #level2type=N''COLUMN'',#level2name=N''' + 'id' + '''' + char(13) + char(10) + 'GO'
EXEC(#sql)
but I got an error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'GO'
Where is my mistake?
Thanks big to all. I have fixed the problem by changed GO to semicolon. Thanks again

Alter Schema Transfer fails even when I'm a db-owner

I asked this on GitHub here, but I think we can turn into a more generic question to get some helpful ideas faster.
First, I ran the script here, which shows that I am a member of the db-owner group.
This is on the install script for an older tool called AutoEdit. Despite the issue below, I'm able to turn on AutoAudit for specific tables and it's working okay.
The supplied script stores a few stored proc under a schema with my username, then tries to transfer them to the "audit" schema later. The AutoEdit concepts and stored procs are all actually working, but now I need to clean it up and put in another environment.
Error is:
Cannot find the object 'pAutoAudit', because it does not exist or you do not have permission.
It created the stored proc as
"Corp\myuserid.pAutoAudit"
I added two print statements to help debug:
-- This is the line of code (the EXEC below) that is causing the issue:
print Concat('#AuditSchema=', #AuditSchema)
SET #Sql = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER dbo.pAutoAudit'
print Concat('#Sql=', #Sql)
EXEC (#Sql)
Above shows:
#AuditSchema=Audit
#Sql=ALTER SCHEMA [Audit] TRANSFER dbo.pAutoAudit
The schema Audit exists, and it has one stored proc in it: pAutoAuditArchive.
I have added a related question here: SQL Server setting that changes schema from dbo
To fix this specific problem, I saw the correct syntax from the Lauren answer here, like this:
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
The following script temporarily fixes the issue. I have to study more how to fix the original script if indeed it has an error:
use myDbname
Declare #AuditSchema varchar(32)
Declare #OldSchema varchar(32)
Declare #SQL varchar(max)
Set #AuditSchema = 'Audit'
Set #OldSchema = 'Corp\myuser'
-- ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAudit'
print Concat('#SQL=', #SQL)
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditAll'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditDrop'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditDropAll'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditRebuild'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditRebuildAll'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditSetTriggerState'
EXEC (#SQL)
SET #SQL = 'ALTER SCHEMA ' + quotename(#AuditSchema) + ' TRANSFER ' + quotename(#OldSchema) + '.pAutoAuditSetTriggerStateAll'
EXEC (#SQL)
However, to fix the "AutoEdit" script referenced in the question, the problem can be corected by adding this code to AutoEdit or running it before AutoEdit. Apparently, it assumes you are in the "dbo" default_schema. You might have to set the value back to the original value if needed after the script.
DECLARE #SQL2 VARCHAR(max)
SET #SQL2 = 'ALTER USER ' + quotename(current_user) + ' WITH DEFAULT_SCHEMA = dbo'
print Concat('#SQL2=', #SQL2)
exec (#SQL2)
The better fix for when I moved it to another environment, was to change all the "Create Proc xxxx" to "Create Proc dbo.xxxx".

Incorrect Syntax near "=" in Dynamic SQL

Below is the query causing error:
EXECUTE (' UPDATE facetswrk.dbo.ODS_SUBSC_PREM_REPORT ' + ' SET ' + #lcrcolumn_name + ' = ' + #lcrcolumn_total)
Your syntax is ok, probably you have wrong valye for column name, or you need to cast #lcrcolumn_tot as nvarchar.
Give us the value for the variable, pr check by yourself with the flowing statement:
declare #lcrcolumn_name nvarchar(50) = 'blabla',
#lcrcolumn_tot nvarchar(50) = 10
declare #sql nvarchar(4000);
set #sql = ' UPDATE facetswrk.dbo.ODS_SUBSC_PREM_REPORT SET ' + #lcrcolumn_name + ' = ' + #lcrcolumn_tot
print #sql
execute(#sql)
Best is to print the dynamic sql before you execute it to understand what is causing the error, you may have some data value in #lcrcolumn_name and #lcrcolumn_total which may be creating the problem.

Execute dynamic SQL queries [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I need to execute a SQL like bellow inside a SP.
DECLARE
#varSearchQ VARCHAR(100),
#varFieldName VARCHAR(100),
#varTableName VARCHAR(100),
#Sql VARCHAR(Max)
SET #varSearchQ='000'
SET #varFieldName='varConsoleID'
SET #varTableName='FF.ConsoleDT'
SET #Sql = N'SELECT ' + #varFieldName + '
FROM ' + #varTableName + '
WHERE ' + #varFieldName + ' LIKE %' + #varSearchQ + '%'
I found a way like EXEC sp_executesql #Sql. But I'm getting errors.
Try this
You Should Use Print for Debugging Statments
Create proc MYPROC
as
BEGIN
DECLARE
#varSearchQ VARCHAR(100),
#varFieldName VARCHAR(100),
#varTableName VARCHAR(100),
#Sql VARCHAR(Max)
SET #varSearchQ='000'
SET #varFieldName='varConsoleID'
SET #varTableName='FF.ConsoleDT'
SET #Sql = N'SELECT ' + #varFieldName + '
FROM ' + #varTableName + '
WHERE ' + #varFieldName + ' LIKE ''%' + #varSearchQ + '%'''
print (#Sql)
EXEC (#Sql)
END

SQLServer conditional execution within 'EXEC' if a column exists

I'm new to SQLServer scripting (normally being a C++ developer), and would really appreciate a bit of assistance.
I am attempting to perform a "find and replace" update on all tables in a SQLServer database that contain a 'PROJID' column. I am really struggling to find a way to do this that doesn't report to me:
Msg 207, Level 16, State 1, Line 1 Invalid column name 'PROJID'.
The statement I am executing is:
EXEC
(
'IF EXISTS(SELECT * FROM sys.columns WHERE name = N''PROJID'' AND Object_ID = Object_ID(N''' + #TableName + '''))' +
' BEGIN' +
' UPDATE ' + #TableName +
' SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ',''' + #ReplaceIDStr + ''',''' + #FindIDStr + ''')' +
' WHERE ' + #ColumnName + ' LIKE ''' + #ReplaceIDStr + '''' + ' AND PROJID = ''1000''' +
' END'
)
I have also tried using:
'IF COL_LENGTH(''' + #TableName + ''',''PROJID'') IS NOT NULL' +
instead of the column-exist check above. This also still gives me the "Invalid Column Name" messages.
I would be happy to take the column-exist check outside of the 'Exec' statement, but I'm not sure how to go about doing this either.
You just need to do it in a different scope.
IF EXISTS (SELECT 1 FROM sys.columns ...)
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'UPDATE ...';
EXEC sp_executesql #sql;
END
Output the results of this query to text. Don't forget to change the values of the variables! Take the result of this and run it.
SET NOCOUNT ON
DECLARE #ColumnName VARCHAR(200) = 'ReplaceColumn'
, #ReplaceIdStr VARCHAR(200) = 'ExampleReplaceIdStr'
, #FindIdStr VARCHAR(200) = 'ExampleFindIdStr'
PRINT 'BEGIN TRAN'
PRINT 'SET XACT_ABORT ON'
SELECT
'UPDATE ' + C.TABLE_NAME + CHAR(13)
+ 'SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ', ''' + #ReplaceIdStr + ''', ''' + #FindIdStr + ''')' + CHAR(13)
+ 'WHERE ' + #ColumnName + ' LIKE ''%' + #ReplaceIdStr + '%'' AND PROJID = ''1000''' + CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = 'PROJID'
PRINT 'COMMIT TRAN'
SET NOCOUNT OFF
EDIT: Also, some reasoning: You said you want update all tables where they contain a column called PROJID. Your first query just says that if the table #TableName has a PROJID column, then update #ColumnName on it. But it doesn't guarantee that it has #ColumnName on it. The query I gave doesn't check that either, because I'm assuming that all tables that have PROJID also have #ColumnName. If that isn't the case, let me know and I can update the answer to check that. That you're getting an Invalid Column Name error points to #ColumnName not existing.
Your query would have updated one table (#TableName) at most, whereas the one I gave you will update every table that has PROJID. I hope that's what your going for.
EDIT 2: Here is a version that would run it all at once:
DECLARE #ColumnName VARCHAR(200) = 'Value'
, #ReplaceIdStr VARCHAR(200) = 'ExampleReplaceIdStr'
, #FindIdStr VARCHAR(200) = 'ExampleFindIdStr'
DECLARE #Sql NVARCHAR(MAX)
DECLARE UpdateCursor CURSOR FOR
SELECT
'UPDATE ' + C.TABLE_NAME
+ ' SET ' + #ColumnName + ' = REPLACE(' + #ColumnName + ', ''' + #ReplaceIdStr + ''', ''' + #FindIdStr + ''')'
+ ' WHERE ' + #ColumnName + ' LIKE ''%' + #ReplaceIdStr + '%'' AND PROJID = ''1000'''
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE C.COLUMN_NAME = 'PROJID'
OPEN UpdateCursor
FETCH NEXT FROM UpdateCursor
INTO #Sql
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC sp_executesql #Sql
FETCH NEXT FROM UpdateCursor
INTO #Sql
END
CLOSE UpdateCursor
DEALLOCATE UpdateCursor

Resources