闲的写写SQL

时间:2024-11-16 12:35:43
/*
新增
*/
Create Proc AddData
(
),
),
@Values nvarchar(max)
)
as
declare @Sql nvarchar(max)
declare @Field nvarchar(max)
declare @Value nvarchar(max)
set @Sql = ''
set @Field = ''
set @Value = ''

begin try
    set @Sql += 'Insert into ' + @TableName + '('
    )
    begin
        ,charindex(',',@Fields)) + ',';
        ,charindex(',',@Values)) + ''',';

        ,len(@Fields) - charindex(',',@Fields))
        ,len(@Values) - charindex(',',@Values))
    end
    set @Sql += @Field + @Fields + ') values (' + @Value + '''' + @Values + ''')';

    exec @Sql
    Select @@Identity as 'Msg'
end try
begin catch
    select ERROR_MESSAGE() as 'Msg'
end catch
go

/*
修改
*/
Create Table EditData
(
),
),
@Values nvarchar(max),
@UpdateWhere nvarchar(max)--条件必须,如更新全部,则传1=1
)
as
declare @Sql nvarchar(max)
declare @SetFiled nvarchar(max)
declare @Field nvarchar(max)
declare @Value nvarchar(max)
set @Sql = ''
set @SetFiled = ''
set @Field = ''
set @Value = ''

begin try
    if(isnull(@UpdateWhere,'') != '')
    begin
        set @Sql += 'Update ' + @TableName + ' set '
        )
        begin
            ,,charindex(',',@Values)) + '''' + ',';
            ,len(@Fields) - charindex(',',@Fields))
            ,len(@Values) - charindex(',',@Values))
        end
        set @Sql += @SetFiled + @Fields + ' = ' + @Values + ' where ' + @UpdateWhere;
        exec @Sql
        ' as 'Msg'
    end
    else
    begin
        Select '更新条件是必须的,如无条件,请传值“1=1”' as 'Msg'
    end
end try
begin catch
    select ERROR_MESSAGE() as 'Msg'
end catch